JSON编码数组通过Javascript正确解析

时间:2016-12-07 08:48:05

标签: javascript php arrays json parsing

说明

所以从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);
    });    
}

3 个答案:

答案 0 :(得分:1)

解析它是正确的。如果您通过XMLHttpRequest获取文字,则需要在JSON.parse上使用responseText。如果您使用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 , and a3`属性。

$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`...
    });    
}

答案 1 :(得分:1)

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

&#13;
&#13;
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
&#13;
&#13;
&#13;

答案 2 :(得分:0)

在PHP中,您需要 json_encode 您的回复:

$ServerResponse= json_encode($MyJSON);

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

var myJSONObject = JSON.parse(ServerResponse);

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