【发布时间】: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]怎么可能是<...它必须是{ -
使用
$.getJSON你永远不需要JSON.parse响应 - 它已经是一个普通的 ol' javascript 对象
标签: javascript php arrays json parsing