0

我有一个 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); }

当前所在的 HTML id

<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 中的值。怎么了?

4

2 回答 2

1

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

document.getElementById('vara').innerHTML = v1;
document.getElementById('varb').innerHTML = v2;
document.getElementById('varc').innerHTML = v3;
于 2013-06-05T05:35:02.863 回答
0

document.getElementById('vara')返回一个HTMLDivElement,它没有value属性。

您可以使用以下构造进行检查:

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

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

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

value 属性只为HTMLInputElements ( <input type='text' />etc. )定义

于 2013-06-05T05:40:35.147 回答