簡體   English   中英

JSON.parse讀取“ {\\” number \\”:\\“ 7 \\”}

[英]JSON.parse reads “{\”number\“:\”7\"}

嗨,我很難用json_encode()PHP函數生成JSON。 我有一個僅在執行以下操作的.php文件:

<?php
// include_once for a few files here

$address = MyModelClass::getByAtrrId(52);
echo json_encode($address, JSON_HEX_QUOT | JSON_HEX_APOS) ;

結果如下:

{"number":"7"}

然后在另一個文件中有jQuery,可通過以下代碼進行檢索:

$(document).ready(function e() {
    let file_path = 'myJson.php';

    let json = $.getJSON(file_path);
    console.log(json);
    let json_obj = JSON.parse(json);

但是$ .getJSON將此字符串讀取為“ {\\” number \\“:\\” 7 \\“},因此JSON.parse以以下錯誤結尾:

SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

很抱歉,我幾乎100%確信這是初學者的錯誤,但是我沒有找到正確的答案。 任何人都知道可能是什么問題嗎?

我發現很多文章都考慮到了jason_encode的輸入,但是現在我覺得真正的麻煩實際上是輸入到jQuery函數中,但是我仍然無法解決。

如果您的Web服務器發送JSON,則最好相應地設置Content-Type

header("Content-Type: application/json; charset=utf-8");

在客戶端上,您需要執行以下操作:

$(document).ready(function() {
    $.getJSON('myJson.php', function(response) {
        // the response is already parsed by jQuery
        alert(response.number);
    });
}

$.getJSON()是異步的,因此您需要傳遞一個處理函數來處理響應。

暫無
暫無

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

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