簡體   English   中英

將php關聯數組從函數返回到ajax調用,使用json_encode()而不是對象

[英]Returning php associative array from function to ajax call with json_encode() not and object

這是我的第一篇文章,所以如果我遺漏一些內容或者不能很好地解釋自己,我會道歉。 所有這些代碼都在同一個php文件中

我的ajax電話

$.ajax(
{
    type: "POST",
    url: window.location.href,
    data: {func: 'genString'},
    datatype: 'json'
})
.done(function ( response )
{
    console.log( response );
    console.log( repose.string );
});

這屬於頁面上的if語句

if ( isset ($_POST['func'] && $_POST['func'] == 'genString')
{
     exit(json_encode(myFunction()));
}

該功能在頁面上運行

function myFunction()
{
    /* Would generate a string based on the database */
    $arr = array('rows' => 1, 'string' => 'My test string');
    // Changes values in the array depending on the database
    return $arr;
}

運行此函數以在頁面本身加載時生成數組,並使用字符串部分顯示它,並使用行部分設置瀏覽器中文本區域的高度,但是當ajax被稱為console.log(respose)這記錄{"rows":1,"string":"My test string"}而不是對象

但是,當我嘗試記錄或使用字符串console.log( response.string ); 它顯示為未定義

我以前做過這個並且它已經工作並返回了一個對象,我可以在js中使用response.string 我試圖使用JSON_FORCE_OBJECT這對結果沒有影響

現在,響應只是被視為一個字符串(數據類型)。 這就是為什么response.string不起作用的原因。

您可以通過添加以下內容來說明:

console.log( typeof response );

所以別忘了放:

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

在你里面if阻止:

而你在if塊(isset和response )上有一個拼寫錯誤:

if ( isset ($_POST['func']) && $_POST['func'] === 'genString' ) {
    header('Content-Type: application/json');
    exit(json_encode(myFunction()));
}

關於JS拼寫錯誤:

console.log( response.string );
               ^^

嗯,這是一個語法錯誤。 請求選項

datatype: 'json' 

應該

dataType: 'json'

暫無
暫無

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

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