2010-08-11 39 views
2

对不起,如果这是基本的,但我一直在处理整天搞清楚这一点,并已经到了我可以用Jquery和cakephp做我需要的一切的地方(不知道cakephp是否重要这或者如果它同任何PHP),我想返回从CakePHP的功能jQuery的一个变量,我读了关于如何做到这一点,就像这里:Jquery,阅读从PHP接收的JSON变量

CakePHP的:

$test[ 'mytest'] = $test; 
echo json_encode($test); 

和jquery:

$.ajax({ 
    type: 'POST', 
    url: 'http://localhost/site1/utilities/ajax_component_call_handler', 
    data: { 
     component_function: component_function, 
     param_array: param_array 
     }, 
     dataType: "json", 
    success: function(data) { 
    // how do i get back the JSON variables? 
    } 
}); 

我只是不知道如何获得一个或多个变量回到可用的形式在jQuery中,我只是想变量,所以我可以做任何事情与它,我一直在寻找我可以通过搜索找到,但它没有使我完全清楚..感谢您的任何建议。

+0

ÁlvaroG.Vicarios的答案是正确的 - 但请注意,您使用的PHP JSON示例将返回{“mytest”:null},因为您将空变量$ test分配给数组$ test – becquerel 2010-08-11 07:07:10

回答

1

你的变量数据。

$.ajax({ 
    type: 'POST', 
    url: 'http://localhost/site1/utilities/ajax_component_call_handler', 
    data: { 
     component_function: component_function, 
     param_array: param_array 
     }, 
     dataType: "json", 
    success: function(data) { 
    // how do i get back the JSON variables? 
     var values = eval(data); //if you 100 % trust to your sources. 
    } 
}); 
+1

当您指定dataType“json”时,jQuery将自动解析JSON。所以没有必要eval()它。 – becquerel 2010-08-11 07:08:27

2

JSON变量位于data变量中。在你的情况下,它会是这样的:

var data = { 
    myTest: "Whatever you wrote here" 
}; 

...所以你可以从data.myTest阅读。

(不知道它是否是相关的,但你可以从URL中移除http://localhost/部分; AJAX不允许跨域请求无论如何)

+0

谢谢..将尝试这样做..是的,删除域名一旦脱离测试阶段,绝对有好处,因为域名可能会更改/在不同的URL中使用 – Rick 2010-08-11 07:08:42

0

基本上数据变量包含json字符串。要分析它,并再次将其转换为JSON,你必须做以下几点:

$.ajax({ 
    type: 'POST', 
    url: 'http://localhost/site1/utilities/ajax_component_call_handler', 
    data: { 
     component_function: component_function, 
     param_array: param_array 
     }, 
     dataType: "json", 
    success: function(data) { 
    json = $.parseJSON(data); 
    alert(json.mytest); 
    } 

我还没有测试,但它应该以这种方式工作。

0

请注意,当您指定dataType“json”或使用$。 getJSON(而不是$。ajax)jQuery将应用$。 parseJSON自动。

所以在“成功”回调你不需要再次使用parseJSON解析响应:

success: function(data) { 
alert(data.mytest); 
} 
0

在返回回JSON变量来查看文件的情况下,你可以使用JavaScript帮手:

在您的事业控制器:

function ajax_component_call_handler() { 
    $this->layout = 'ajax'; 
    if($this->RequestHandler->isAjax()) { 
     $foobar = array('Foo' => array('Bar')); 
     $this->set('data', $foobar); 
    } 
} 

,并在您的视图/公共事业/ ajax_component_call_handler.ctp你可以使用:

if(isset($data)) { 
    $javascript->object($data); //converts PHP var to JSON 
} 

所以,当你达到你的功能阶段:

success: function(data) { 
    console.log(data); //it will be a JSON object.  
} 

在这种情况下,你会从控制器和视图逻辑分离变量类型处理(如果你还需要别的东西,然后JSON) ...