【问题标题】:How would I go about doing this?我该怎么做呢?
【发布时间】:2012-05-26 09:19:16
【问题描述】:

首先我在 json_encode 函数中编码了我的数据。

例如看起来像这样:

{"test":"test value"}

我想做的是将测试变成一个javascript变量,它可以保存“测试值”的数据。

【问题讨论】:

  • var foo = {"test":"test value"}...不知道你在问什么
  • 很抱歉不够具体,但 json_encode 数据在一个页面上,而使用 javascript 的页面在另一个页面上。因此,例如 json_encode 数据将在 index.php 上,而带有 javascript 变量的页面将是 example.html
  • 似乎stackoverflow正在成为家庭作业热线......

标签: ajax xmlhttprequest json


【解决方案1】:

index.php(在这里使用json_encode):

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

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解决方案):

<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>

【讨论】:

  • 如果我没记错那不是用jquery吗?
  • 我不能使用 jQuery,因为这是我项目的限制。
【解决方案2】:
$.getJSON('ajax/test.json', function(data) {
  var items = [];

  $.each(data, function(key, val) {
    items.push('<li id="' + key + '">' + val + '</li>');
  });

  $('<ul/>', {
    'class': 'my-new-list',
    html: items.join('')
  }).appendTo('body');
});

直接来自 jquery 文档...

【讨论】:

  • 谢谢大卫,我也打算在那里添加评论。
【解决方案3】:

对象是关联数组。它们存储键/值对。所以你所要做的就是:

var test = function(){}
test["hello"] = "world";

这会将hello 设置为变量,并将world 设置为其值。 你可以通过这样做来测试它

alert(test.hello);

helloworld 替换为 json 键和值

希望对这个例子有更多帮助: 我正在使用 Jquery AJAX 转到 index.php 资源并返回一个 json 对象。

index.php

<?php
$variables = array('hello' => 'world');
echo json_encode($variables);
?>

example.html

var test = function(){}
$.ajax({
   url: index.php,
   success: function(json) {
    for(var key in json ){
     var testVarName = key;
     var testVarValue = json[key];
     test[testVarName ] = testVarValue;
    }
}
});

所以现在test 对象有变量hello,它的值是world

【讨论】:

  • 好吧,我在其他文档中提到我不能使用 jquery,因为这是我项目中的一个限制。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-14
相关资源
最近更新 更多