我怎么会去这样做呢? [英] How would I go about doing this?

查看:147
本文介绍了我怎么会去这样做呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我必须在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>

这篇关于我怎么会去这样做呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆