【问题标题】:Using JQuery to get JSON response from PHP使用 JQuery 从 PHP 获取 JSON 响应
【发布时间】:2013-10-15 18:57:42
【问题描述】:

我现在已经积累了大约五六个不同的教程,我仍然无法找出问题所在!

使用 JQuery Mobile (phonegap) 向 PHP 服务器发送和接收数据。我似乎无法让 JQuery 脚本获得响应。 服务器上的 PHP:

<?php

// Set up associative array
$data = array('success'=> true,'message'=>'Success message: worked!');

// JSON encode and send back to the server
echo json_encode($data);

?>

JQuery 函数(被调用):

<script type="text/javascript">
$(function () {
    $('#inp').keyup(function () {
        var postData = $('#inp').val();
        $.ajax({
            type: "POST",
            dataType: "json",
            data: postData,
            beforeSend: function (x) {
                if (x && x.overrideMimeType) {
                    x.overrideMimeType("application/json;charset=UTF-8");
                }
            },
            url: 'removedmyurlfromhere',
            success: function (data) {
                // 'data' is a JSON object which we can access directly.
                // Evaluate the data.success member and do something appropriate...
                if (data.success == true) {
                    alert('result');
                    $('.results').html(data.message);
                } else {
                    $('.results').html(data.message);
                }
            }
        });
    });
});
</script>

抱歉格式化,这一切都是成对复制的。删除了我的网址。

我知道该函数正在触发,因为如果我删除了 alert('here');并将其放在它显示的 ajax 调用之上。

有人知道为什么没有调用成功函数吗?任何浏览器上的类结果都不会在 div 中显示。

谢谢!

【问题讨论】:

  • 在进行 ajax 调用时,您在浏览器中得到什么响应?你真的得到了 200 响应吗?这是跨域请求吗?
  • 这只是一个具有如下关联的数组:{"success":true,"message":"Success message: hooray!"} 添加 tak3er 建议的标头我得到一个 .json 文件文件存储在本地,除了存储在网页外部服务器上的 php 文件。
  • 我怀疑是跨域请求
  • 我尝试过使用 jsonp 并添加回调参数。这也不起作用
  • @WelshJohn 因此,您是说在使用浏览器的开发工具(或 Firebug 或类似工具)查看 AJAX 调用的响应信息时,您会收到带有您期望的 JSON 正文的 200 响应?

标签: javascript php jquery json cordova


【解决方案1】:

嘿,我遇到了同样的问题

首先我使用了 $.getJSON blah blah....但由于某种原因没有工作...

但是正常的 ajax 调用有效.. MY Page 返回一个 json 输出为您.. 尝试删除 "datatype"

我使用了从JQUERY 网站复制的代码,在我粘贴的下方

$.ajax({
  type: "POST",
  url: "some.php",
  data: { name: "John", location: "Boston" }
})
  .done(function( msg ) {
    alert( "Data Saved: " + msg );
  });

以下是我如何使用和处理我得到的 json 输出的代码...

$.ajax({
          type: "GET",
          url: "json.php",
          data: { searchword: q, projid:prid }
        })
          .done(function( jsonResult ) {
            var str='';
        for(var i=0; i<jsonResult.length;i++)
          {
              //do something here.. with jsonResult."yournameof "
            alert(jsonResult[i].id+jsonResult[i].boqitem);
          }
});

【讨论】:

    【解决方案2】:

    在这里记住相同的域来源,使用带有回调的 jsonp 对我一直很有帮助,这确实意味着在您的 php 脚本中添加 $_GET['callback'] 并使用 '('.json_encode($Array).')' 包装 json_encode 以进行正确的格式化。

    http://api.jquery.com/jQuery.getJSON/

    该页面上的最后一个演示是我找到的最佳示例。

    【讨论】:

      【解决方案3】:

      看起来像跨域请求。

      通过改变来尝试:

      dataType : "json"
      

      dataType : "jsonp"
      

      【讨论】:

        【解决方案4】:

        我知道已经很晚了。但它可以简单地处理

        var postData = {'inp': $('#inp').val()};
        $.ajax({
            type: "POST",
            data: postData,
            url: 'removedmyurlfromhere', // your url
            success: function (response) {
                // use exception handling for non json response
                try {
                    response = $.parseJSON(response);
                    console.log(response); // or whatever you want do with that
                } catch(e) {}
            },
            error: function( jqXHR, textStatus, errorThrown ) {},
            complete: function(  jqXHR, textStatus ) {}
        });
        

        【讨论】:

          【解决方案5】:

          在 PHP 中,添加 JSON 内容类型标头:

          header('Content-Type: application/json');
          

          另外,试着听完整的,看看你是否确实得到任何回应:

          $.ajax({
          
           // ....
           complete: function (xhr, status) {
             $('.results').append('Complete fired with status: ' + status + '<br />');
             $('.results').append('XHR: ' + (xhr ? xhr.responseText : '(undefined)'));
           }
           // ...
          
          });
          

          【讨论】:

          • 添加了上面的标题并且没有变化。没有警报,也没有 div 中的结果。现在直接访问页面会导致打开或保存 .json 文件。
          • 虽然添加标头是个好主意,但如果您在 ajax 选项中提供了 dataType,则不需要。
          • 文件打开是因为您的浏览器不理解 json mime 类型。您是否看到我编辑后的回复并调用完成:看看您是否收到回复?
          • 完整函数触发并产生 Complete Fired!在相应的div中。
          • 好酷。这意味着您的代码正在运行,但响应有问题。您有 2 个选项:您收到的回复与 200 OK 不同,或者您的 JSON 无效。如果您有 Google chrome 或 Firefox 和 firebug,这将非常有用。打开 devtools/firebug,转到网络选项卡并单击您发出的请求以查看响应。我还更新了 js 代码以包括打印状态和响应
          猜你喜欢
          • 2012-04-21
          • 1970-01-01
          • 2017-12-20
          • 1970-01-01
          • 1970-01-01
          • 2012-10-15
          • 2022-06-28
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多