无法在HTML页面AJAX中打印JSON响应

时间:2013-06-05 05:27:13

标签: javascript ajax json

我有一个AJAX功能如下:

function ajx(){
var ajaxRequest;  // The variable that makes Ajax possible!


try{
    // Opera 8.0+, Firefox, Safari
    ajaxRequest = new XMLHttpRequest();
} catch (e){
    // Internet Explorer Browsers
    try{
        ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try{
            ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e){
            // Something went wrong
            alert("Your browser broke!");
            return false;
        }
    }
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
       // alert(ajaxRequest.readyState);
    if(ajaxRequest.readyState == 4){
                    //alert(ajaxRequest.responseText);

                    var res = ajaxRequest.responseText;


                    var a = JSON.parse(res);


                    var v1 = a[0];
                    var v2 = a[1];
                    var v3 = a[2];

                    //alert(v1);

                    document.getElementById('vara').value = v1;
                    document.getElementById('varb').value = v2;
                    document.getElementById('varc').value = v3;


    }
}

ajaxRequest.open("GET", "ajax.php", true);
ajaxRequest.send(null); }

存在id的HTML:

<div id="vara"></div>
<div id="varb"></div>
<div id="varc"></div>

相应的ajax.php是:

 <?php

$resp = array('man','cow','dog');

echo json_encode($resp);

?>

如果我提醒v1 v2v3,则会分别显示mancowdog。但它不是在HTML中打印值。怎么了?

2 个答案:

答案 0 :(得分:1)

您正在div上创建一个名为value的新属性,因为它们没有value属性。您想要设置innerHTML或innerText:

document.getElementById('vara').innerHTML = v1;
document.getElementById('varb').innerHTML = v2;
document.getElementById('varc').innerHTML = v3;

答案 1 :(得分:0)

document.getElementById('vara')返回HTMLDivElement,其中没有value属性。

您可以使用构造来检查:

'value' in document.getElementById('vara'); //false

请改用innerHTML属性,HTMLDivElement继承自HTMLElement

'innerHTML' in document.getElementById('vara'); //true

value属性仅定义为HTMLInputElement s(<input type='text' />等)