使用JQuery从PHP获取JSON响应

时间:2022-10-08 18:17:32

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. I cannot seem to get the JQuery script to pick up a response. PHP on server:

使用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 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'); and put it above the ajax call it displays.

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

Anybody know why the success function isn't calling? nothing shows in the div with class results on any browser.

有谁知道为什么成功功能没有调用? div中没有​​显示任何浏览器上的类结果。

Thanks!

5 个解决方案

#1


0  

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调用工作..我的Page返回一个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);
          }
});

#2


0  

In PHP, add the JSON content-type header:

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

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)'));
 }
 // ...

});

#3


0  

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 。')'正确格式化。

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

The last demo on that page is the best example I have found.

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

#4


0  

Looks like cross domain request.

看起来像跨域请求。

Try it by changing :

通过更改来尝试:

dataType : "json"

to

dataType : "jsonp"

#5


0  

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

#1


0  

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调用工作..我的Page返回一个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);
          }
});

#2


0  

In PHP, add the JSON content-type header:

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

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)'));
 }
 // ...

});

#3


0  

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 。')'正确格式化。

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

The last demo on that page is the best example I have found.

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

#4


0  

Looks like cross domain request.

看起来像跨域请求。

Try it by changing :

通过更改来尝试:

dataType : "json"

to

dataType : "jsonp"

#5


0  

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