简体   繁体   English

使用JQuery从PHP获取JSON响应

[英]Using JQuery to get JSON response from PHP

I have accumulated and chopped up about 5 or 6 different tutorials of this now, and I still can't find out what's wrong! 现在,我已经积累并砍掉了大约5或6个不同的教程,但我仍然无法找出问题所在!

Using JQuery Mobile (phonegap) to send and receive data to a PHP server. 使用JQuery Mobile(phonegap)向PHP服务器发送和接收数据。 I cannot seem to get the JQuery script to pick up a response. 我似乎无法让JQuery脚本接收响应。 PHP on server: 服务器上的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 Function (Which is being called): 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>

Sorry for the formatting, it all went pair shaped copying it across. 很抱歉格式化,所有格式都成对复制。 Removed my url. 删除了我的网址。

I know that the function is firing, because if I remove the alert('here'); 我知道该函数正在触发,因为如果我删除了alert('here'); and put it above the ajax call it displays. 并将其放在显示的ajax调用上方。

Anybody know why the success function isn't calling? 有人知道为什么不调用成功函数吗? nothing shows in the div with class results on any browser. 在任何浏览器中,类结果都不会显示在div中。

Thanks! 谢谢!

In PHP, add the JSON content-type header: 在PHP中,添加JSON content-type标头:

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

also, try listening for complete as well to see if you do get any response back: 另外,尝试聆听完整,以及如果得到任何回应回过头来看看:

$.ajax({

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

});

Keep same domain origins in mind here, use jsonp with a callback has always been helpful for me, that does mean adding a $_GET['callback'] to your php script and wrap the json_encode with '('.json_encode($Array).')' for proper formatting. 在这里请记住相同的域起源,将jsonp与回调一起使用对我一直很有帮助,这意味着向您的php脚本中添加$_GET['callback']并使用'('.json_encode($Array).')'包裹json_encode '('.json_encode($Array).')'进行正确格式化。

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

The last demo on that page is the best example I have found. 该页面上的最后一个演示是我找到的最佳示例。

Hey i had the same problem 嘿,我有同样的问题

Firstly i used $.getJSON blah blah.... but didn't worked for some reason... 首先我用$ .getJSON等等....但是由于某些原因没有工作...

But the normal ajax call worked.. MY Page returns a json output as you.. try removing the "datatype" 但是正常的ajax调用是有效的。我的页面会在您返回json输出时尝试删除“数据类型”

I Used code copied from JQUERY site which is below i pasted 我使用了从我下面粘贴的JQUERY网站复制的代码

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

Below is the code how i used and worked with json output i got... 以下是我如何使用并与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);
          }
});

Looks like cross domain request. 看起来像跨域请求。

Try it by changing : 通过更改尝试:

dataType : "json"

to

dataType : "jsonp"

I know it is very late. 我知道已经很晚了。 But it can simply be handled like 但是它可以像

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 ) {}
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM