用从php接收到的JS解析json数据

Parse json data with JS being received from php

本文关键字:JS 解析 json 数据 php 用从      更新时间:2023-09-26

我的表单:

          <form class="form-inline signup" action="php/signupForm.php" role="form" id="signupForm">
        <div class="form-group">
          <input type="email" name="email" class="form-control" placeholder="Email address">
        </div>
        <div class="form-group">
          <button type="submit" class="btn btn-theme ladda-button" data-style="expand-left">
<span class="ladda-label" id="notice">Get notified!</span>
</button>
        </div>
      </form>

结束我的PHP脚本

$response = array(
    "status" => $status,
    "message" => $message
);
echo json_encode($response);

我的页面正在接收如下数据:

{"status":0,"message":"This email is already on list!"}

使用JS,我需要解析这些数据,然后更新元素中的文本。

 <span id="notice">Get notified!</span>

这是我的脚本,它不工作,后发送表单数据到我的php脚本,我得到一个白屏,显示json强

    $(document).ready(function() {
      $.ajax({
      dataType: 'json',
        $('#notice').text(data.message);
      });
    });

您必须在回调中处理响应。

$(document).ready(function() {
    $('form').on('submit', function(e) {
        e.preventDefault();
        $.ajax({
          data: $(this).serialize(),
          url: $(this).attr('action'), // Or the path of the PHP file
          dataType: 'json',
        }).done(function(response) {
          $('#notice').text(response.message);
        });
    });
});

请参阅此处的相关文档

ajax调用格式不正确,缺少成功回调和url,例如:

$(document).ready(function () {
    $.ajax({
        url: '/the/url/where/your/data/comes/from/',
        dataType: 'json',
        success: function (data) {
            $('#notice').text(data.message);
        }
    });
});

您的代码是,只是在页面加载执行,而不是在提交表单。您需要附加一个onsubmit事件,防止默认的表单提交操作,并在其中执行ajax调用。此外,您的ajax调用本身是畸形的

$("#yourFormID").submit(function(e){
    e.preventDefault();
    $.ajax({
       url:"/urlToServerScript",
       data:{} //any form data the script needs you should be put here,
       dataType:"json" //type of response the server will output
    }).then(function(data){
       $('#notice').text(data.message);
    });
});