我怎么会去这样做呢?这样做、会去、我怎么

2023-09-10 15:53:54 作者:空城旧梦

首先,我必须在json_en code函数我的数据连接codeD。

First I have my data encoded in the json_encode function.

看起来是这样,例如:

{"test":"test value"}

我想要做的就是让考不上一个JavaScript变量在那里可以容纳的测试值。

What I want to do is make test into a javascript variable where it can hold the data of "test value".

推荐答案

index.php文件(使用 json_en code 点击这里):

index.php (use json_encode here):

<?php
  $foo = array('test' => 'test value');
  echo json_encode($foo);
?>

example.html

example.html

<script type="text/javascript">

  $.get('index.php', function(response) {
    alert(response['test']);
    // this will alert "test value"
  }, 'json');

</script>

EDIT1 :example.html的(不-jQuery的解决方案的):

EDIT1: example.html (without-jQuery solution):

<script type="text/javascript">

window.onload = function() {
    var request;
    request = getHTTPObject();
    request.onreadystatechange = sendData;
    request.open("GET", "index.php", true);
    request.send(null);
}

function sendData() {
    if(request.readyState == 4){
    var JSONtext = request.responseText;
    var JSONobject = JSON.parse(JSONtext);

    // notice how variables are used
    var output = JSONobject.test;

    alert(output); // displays "test value"
}


function getHTTPObject(){
    var xmlhttp = false;
    if(window.XMLHttpRequest){
        xmlhttp = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        try{
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch(e){
            try{
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(e) {
                xmlhttp = false;
            }
        }
    }
    return xmlhttp;
}
</script>