簡體   English   中英

解碼從Ajax返回的javascript中的json對象

[英]Decoding json object in javascript that is returned from ajax

我已經用json_encode在php中為ajax返回准備了一個數組。 通過ajax返回時,它的行為不符合我的預期。

Ajax調用和我嘗試詢問結果

$.ajax({

     url:"dbpaginate.php",
              type:"POST",
              data: {'environmentvars': tmp},
    cache: false,

    success: function(response){
        alert('Returned from ajax: ' + response);
        alert(response["actionfunction"]);
        $j.each(response, function (index,element) {
            alert(index);
            alert(element);


        });
});

第一條警報消息:

Returned from ajax: array(5) {
["actionfunction"]=>
string(8) "showData"
["sortparam"]=>
string(6) "ticker"
["sortorder"]=>
string(3) "ASC"
["page"]=>
int(1)
["htmlstring"]=>
string(0) ""
}
{"actionfunction":"showData","sortparam":"ticker","sortorder":"ASC","page":1,"htmlstring":"","htmltext":"<table id=\"summaryheader\"> [...lots of html...]<\/div>\n"}

第二條警報消息

undefined

預期結果

showData

如何有效地將json response移植到javascript對象environmentvars中? 謝謝。

您必須使響應為有效的JSON。 似乎您在服務器端腳本中的某處有一條print_r語句,其輸出包含在響應中。 刪除它。

響應始終是文本,即JavaScript中的字符串。 您可以在添加數據之前解析JSON(在JavaScript中解析JSON? ),或者通過添加dataType: 'json'選項告訴jQuery為您解析。

您應該在此類方法中指定一個dataType參數,該參數基本上用於聲明您希望從服務器獲取的數據類型。

這是一個例子:

$.ajax({
  type: "POST",
  url: <your-request-url>,
  data: <your-data>,
  success: function(){ ... },
  dataType: "json"
});

此處有更多詳細信息: https : //api.jquery.com/jquery.post/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM