【问题标题】:JSON encode array parse correctly via JavascriptJSON编码数组通过Javascript正确解析
【发布时间】:2016-12-07 08:48:04
【问题描述】:

解释

所以从 PHP 到 JavaScript 编码的 JSON 数组发送如下:

$qa = array('question' => $question, 'a1' => $answer1, 'a2' => $answer2, 'a3' => $answer3);

echo json_encode($qa, JSON_UNESCAPED_UNICODE);

当我在 JavaScript 中这样使用时(看看drawOutput):

function getSuccessOutput() {
  getRequest(
      't.php', // demo-only URL
       drawOutput,
       drawError
  );
  return false;
}

function drawOutput(responseText) {   
    var container = document.getElementById('output');
    container.innerHTML = responseText;
}

function getRequest(url, success, error) {
    var req = false;
    try{
        // most browsers
        req = new XMLHttpRequest();
    } catch (e){
        // IE
        try{
            req = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            // try an older version
            try{
                req = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                return false;
            }
        }
    }
    if (!req) return false;
    if (typeof success != 'function') success = function () {};
    if (typeof error!= 'function') error = function () {};
    req.onreadystatechange = function(){
        if(req .readyState == 4){
            return req.status === 200 ? 
                success(req.responseText) : error(req.status)
            ;
        }
    }
    req.open("GET", url, true);
    req.send(null);
    return req;
}   

我得到以下输出:

{"question":"This is my question?","a1":"answer1","a2":"answer2","a3":"answer3"} 

期望的结果

我需要从这个数组中提取每个值并分配给变量,例如:

var myQuestion = "This is my question?";
var answ1 = "answer1";
var answ2 = "answer2";
var answ3 = "answer3";

我的尝试

function drawOutput(responseText) {   
    var container = document.getElementById('output');

    container.innerHTML = responseText;
    // OUTPUT: {"question":"This is my question?","a1":"answer1","a2":"answer2","a3":"answer3"} 

    container.innerHTML = responseText[0];
    // OUTPUT: <

    container.innerHTML = responseText[a1];
    // OUTPUT: nothing (blank)    
}

我也试过了:

function drawOutput(responseText) {
    $.getJSON("t.php", function(responseText){      
        var container = document.getElementById('output');
        var theObject = JSON.parse(responseText);
    container.innerHTML = theObject[a1];        
    });    
}
// OUTPUT: nothing (blank)

在这种情况下,我还尝试使用var theObject = JSON.parse(JSON.stringify(responseText)); 而不是var theObject = JSON.parse(responseText); 输出:undefined

如果我在以下使用:

function drawOutput(responseText) {             
    var container = document.getElementById('output');
    var theObject = JSON.parse(responseText);
    container.innerHTML = theObject[a1];                
}
// Output: nothing (blank)

但我在浏览器的控制台中遇到错误:SCRIPT1014: Invalid character

我已经阅读了许多类似的问题,但对我的情况没有任何帮助。你有什么想法,我该如何解决?

更新

这就是我现在正在尝试的,没有任何输出(空白):

function drawOutput(responseText) {
    $.getJSON("t.php", function(responseText){     
        var question = theObject.question;        // Get the question
        var a1       = theObject.a1;              // Get the answers
        var a2       = theObject.a2;
        var a3       = theObject.a3;

        var container = document.getElementById('output');
        container.innerHTML = a1;
        alert(a1);
    });    
}

【问题讨论】:

  • 这是一个对象,所以尝试使用 responseText.a1 或 responseText['a1']
  • 你能控制台记录var theObject吗?
  • 如果responseText{"question":... responseText[0] 怎么可能是&lt; ...它必须是{
  • 使用 $.getJSON 你永远不需要 JSON.parse 响应 - 它已经是一个普通的 ol' javascript 对象

标签: javascript php arrays json parsing


【解决方案1】:

解析它是正确的。如果您通过XMLHttpRequest 获取文本,则需要在responseText 上使用JSON.parse。如果你使用 jQuery 的$.getJSON,它会为你做这件事并给你解析的结果。

问题在于您如何尝试从结果中访问值。在theObject[a1] 中,您尝试使用一个名为a1变量,然后将其值用作要获取的属性的名称。请改用theObject.a1theObject["a1"]

所以在这里,您正在使用getJSON,所以它已经为您解析了:

function drawOutput() {
    $.getJSON("t.php", function(theObject){       // Note: Not `responseText`, a parsed object
        var question = theObject.question;        // Get the question
        var a1       = theObject.a1;              // Get the answers
        var a2       = theObject.a2;
        var a3       = theObject.a3;
        // ...use them...
    });    
}

旁注:您可以考虑使用数组,而不是在要返回的对象上使用单独的 a1,a2, anda3` 属性。

$qa = array(
    'question' => $question,
    'answers' => array($answer1, $answer2, $answer3)
);
echo json_encode($qa);

然后

function drawOutput() {
    $.getJSON("t.php", function(theObject){      
        var question = theObject.question;        // Get the question
        var answers  = theObject.answers;         // Get the answers
        // ...use question, and `answers[0]` through `answers[2]`, where
        // you can get the number of answers from `answers.length`...
    });    
}

【讨论】:

  • @JaromandaX:这似乎是一个简单的“将数据从这里发送到那里”,没有任何迹象表明复杂的版本也没有固定的字段名称。
  • 感谢您的回答,但是当我尝试在您评论 // ...use them... 的地方使用 alert(a1);var container = document.getElementById('output'); container.innerHTML = a1; 时,什么也没有发生
  • 另外我不认为我正在使用XMLHttpRequest,这几乎是我在 PHP 和 JavaScript 中使用的所有代码(附在 index.html 中的 javascript,我不知道这是否重要)。
  • @Infinity:抱歉,我抓住了你的一个使用 getJSON 的代码 sn-ps,但没有注意到(因为它在 drawOutput 上有 responseText 参数) .我刚刚修复了上面的问题。我在答案中说过,但为了强调:如果您直接使用XMLHttpRequest,则需要JSON.parse。如果你使用 jQuery 的$.getJSON,jQuery 会为你做解析。
  • @Infinity:如果您返回的资源带有正确的Content-Type 标头指示正在使用的字符集,那应该没问题。
【解决方案2】:

您可以使用以下方法之一访问对象值:

var responseText = '{"question":"This is my question?","a1":"answer1","a2":"answer2","a3":"answer3"} ';
var theObject = JSON.parse(responseText);
console.log(theObject['a1']); // a1 in string
console.log(theObject.a1); // Gives the same result

【讨论】:

  • 感谢您的回答,但与我的问题中的最后一个示例一样,它没有返回任何内容(空白)。在浏览器控制台中,我看到一个错误 SCRIPT1014: Invalid character
【解决方案3】:

在 PHP 中,您需要 json_encode 您的响应:

$ServerResponse= json_encode($MyJSON);

在 Javascript 中,您需要 JSON.parse 从 PHP 获得的响应:

var myJSONObject = JSON.parse(ServerResponse);

之后,你手中就有了一个普通的Object,那就是myJsonObject。您可以使用“点”(例如 myJsonObject.PROPERTY_NAME)或括号(例如 myJsonObject[“PROPERTY_NAME”])来访问其属性。

【讨论】:

    猜你喜欢
    • 2011-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多