簡體   English   中英

使用JQuery從PHP獲取JSON響應

[英]Using JQuery to get JSON response from PHP

現在,我已經積累並砍掉了大約5或6個不同的教程,但我仍然無法找出問題所在!

使用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中。

謝謝!

在PHP中,添加JSON content-type標頭:

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

});

在這里請記住相同的域起源,將jsonp與回調一起使用對我一直很有幫助,這意味着向您的php腳本中添加$_GET['callback']並使用'('.json_encode($Array).')'包裹json_encode '('.json_encode($Array).')'進行正確格式化。

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

該頁面上的最后一個演示是我找到的最佳示例。

嘿,我有同樣的問題

首先我用$ .getJSON等等....但是由於某些原因沒有工作...

但是正常的ajax調用是有效的。我的頁面會在您返回json輸出時嘗試刪除“數據類型”

我使用了從我下面粘貼的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);
          }
});

看起來像跨域請求。

通過更改嘗試:

dataType : "json"

dataType : "jsonp"

我知道已經很晚了。 但是它可以像

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