2011-01-26 48 views
0

这对我而言是新东西,请耐心等待。 JQuery & json - 我一直在使用json &序列化在PHP中的“年龄”,但只是进入JQ。我想通过数据跨域 - 所以json数组似乎对我最好,但如何显示它,例如

说我有一个JSON数组像这样在PHP创建了位于http://domain1.com/examplearray.php

$catarray = array('Animal Life','Business & Finance','Cars & Vehicles','Entertainment & Arts','Food & Cooking','Health','History, Politics & Society','Hobbies & Collectibles','Home & Garden','Humor & Amusement','Jobs & Education','Law & Legal Issues','Literature & Language','Relationships','Religion & Spirituality','Science','Shopping','Sports','Technology','Travel & Places'); 
$callback = json_encode($catarray); 

我明白,我可以从另一个域调用它的页面名称examplearray.php说http://domain2.com

$(document).ready(function(){ 
$.getJSON("http://domain1.com/examplearray.php?callback=", 
function(data){ 
$.each(data, function(i,item) 
{ 
// WHAT DO I put in here to read the array? i.e. what are the keys etc. // 
// I assume the display is something like $('#element').html('something'); 
}); 
}); 
}); 

在上面的示例中,如果您遵循该示例,则没有“设置”键,但现在像这样向该阵列添加一个键

$catarray = array('keyname' => array('Animal Life','Business & Finance','Cars & Vehicles','Entertainment & Arts','Food & Cooking','Health','History, Politics & Society','Hobbies & Collectibles','Home & Garden','Humor & Amusement','Jobs & Education','Law & Legal Issues','Literature & Language','Relationships','Religion & Spirituality','Science','Shopping','Sports','Technology','Travel & Places')); 

非常感谢,非常感谢。

回答

1

你需要你的回调后添加?,你需要与回调服务器端来包装你的代码:
examplearray.php:

<?php 
// your data generation routine 
$results = array('Animal Life','Business &amp; Finance','Cars &amp; Vehicles','Entertainment &amp; Arts','Food &amp; Cooking','Health','History, Politics &amp; Society','Hobbies &amp; Collectibles','Home &amp; Garden','Humor &amp; Amusement','Jobs &amp; Education','Law &amp; Legal Issues','Literature &amp; Language','Relationships','Religion &amp; Spirituality','Science','Shopping','Sports','Technology','Travel &amp; Places'); 
if(isset($_REQUEST['callback'])) { 
    $json_callback_func = $_REQUEST['callback']; 
    echo $json_callback_func . '('.json_encode($results).')'; 
} 
?> 

而且你的JS:

$(function() { 
    $ul = $('ul'); 
    $.getJSON("http://domain1.com/examplearray.php?callback=?", function(data){ 
     $.each(data, function(k,v){ 
      $ul.append("<li>" + v + "</li>"); 
     }); 
    }); 
}); 

现在,因为你的阵列是没有索引它是一个数值数组,所以按键k将是唯一索引。

现在,如果你有钥匙,像你的第二个例子,你可能需要使用嵌套循环,或者如果你有确切的情况下,你的榜样,然后使用:

$.each(data.keyname, function(k,v){ 
0

要了解您必须使用哪些变量,您可以尝试在调试器中运行代码,如Chrome中的“Javascript控制台”或Firefox中的Firebug。在$ .each函数中放置一个断点。看看你的局部变量,你应该看到所有可用的数据结构。习惯于在浏览器中使用调试工具。它们可以节省大量时间。

为了更直接地解决你的问题,也有访问使用$。每次(数据很好的例子)这里:http://api.jquery.com/jQuery.getJSON/

“项目,”现在是你的榜样JavaScript对象。您可以使用它本身(item.attribute)