如何在javascript中通过ajax获取php数组?

时间:2014-01-20 08:01:58

标签: javascript php ajax

当我尝试访问 PHP 数组时,我无法访问它。我运行代码时它保持沉默。在这里我使用javascript通过get方法获取php。 createRequest()函数用作创建请求对象。然后getDetails()用于协调displayDetails()和createRequest()。 php文件如下所示。任何帮助都会有所帮助,

function createRequest() {
    try {
        request = new XMLHttpRequest();
    } catch (tryMS) {
    try {
        request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (otherMS) {
    try {
        request = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (failed) {
        request = null;
    }
    }
    }
return request;
}

function getDetails() {
    alert("getDetails");
    request = createRequest();
    if (request==null) {
        alert("Unable to create request");
        return;
    }


    request.open("GET","problems.php",true);
    request.onreadystatechange = displayDetails;
    request.send(null);
}

function displayDetails() {

    if (request.readyState == 4) {
        if (request.status == 200) {

            detailDiv = document.getElementById("description");

            var jsumset = JSON.parse(request.responseText);
            detailDiv.innerHTML = jsumset["rop"];
        }
    }
}


<?php
    include ("sumcreator.php");
    $sumobj = new sumcreator();
    $sumset = $sumobj->sumcreator();

    echo $json_encode($sumset);
?>

2 个答案:

答案 0 :(得分:0)

确保使用UTF8编码。 Json函数需要它,所以如果你使用任何重音字符,你应该让它们utf8_encode -d。

答案 1 :(得分:0)

为什么你用两种方法来做这件事你可以在一个函数中这样做 如果有效,你可以试试这个:

function addMe() {

        theValues = document.getElementById('list2');


         for(i = 0; i < theValues.length; i++) {



                if (   document.getElementById('theNumbers').value == ""   ) {
                    document.getElementById('theNumbers').value ="`"+theValues[i].value+"`";
                } else {
                    document.getElementById('theNumbers').value += ","+"`"  + theValues[i].value+"`";
                }



        }


var jsonString = JSON.stringify(dataString);
//alert(jsonString);
            $('#test').html("");
   $.ajax({
        type: "POST",
        url: "pages/ajaxpage.php",
        data: {data : jsonString}, 
        cache: false,

        success: function(response){



           $('#test').html(response);


        }
    });

    }

    }