javascript 使用 JQuery 从 PHP 获取 JSON 响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19388947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:23:39  来源:igfitidea点击:

Using JQuery to get JSON response from PHP

javascriptphpjqueryjsoncordova

提问by WelshJohn

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.

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

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

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

Thanks!

谢谢!

采纳答案by ivar ajet

Hey i had the same problem

嘿,我有同样的问题

Firstly i used $.getJSON blah blah.... but didn't worked for some reason...

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

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

回答by E-comm

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 与回调一起使用对我来说一直很有帮助,这确实意味着$_GET['callback']在您的 php 脚本中添加 a并用 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.

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

回答by byJeevan

Looks like cross domain request.

看起来像跨域请求。

Try it by changing :

尝试通过更改:

dataType : "json"

to

dataType : "jsonp"

回答by kazimt9

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

回答by Stefan

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 doget any response back:

另外,尝试收听 complete 以查看您是否收到任何回复:

$.ajax({

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

});