简体   繁体   English

使用AJAX返回json数组

[英]Returning a json array using AJAX

Here's the javascript: 这是JavaScript:

var data = $('form#registration-form').serialize();
$.post(
'<?php echo $this->url('/register', 'do_register')?>',
function(data) {
 alert(data);
},
'json'
);

And here's the ending of the do_register() method: 这是do_register()方法的结尾:

if( $_REQUEST['format']=='JSON' ){
$jsonHelper=Loader::helper('json'); 
echo $jsonHelper->encode($registerData);
die;
}

The $registerData variable holds all the data I need. $registerData变量保存我需要的所有数据。 I want the function to return it after the ajax call. 我希望函数在ajax调用后返回它。 However, when I specify dataType: 'json' nothing is returned. 但是,当我指定dataType:'json'时,不会返回任何内容。 Any suggestions? 有什么建议么?

I think your problem is in url 我认为您的问题出在网址中

$.post(
'<?php echo $this->url("/register", "do_register"); ?>?format=JSON',
function(data) {
 alert(data);
},
'json'
);

Also you can use following line in php part to get json values 您也可以在php部分中使用以下行获取json值

header('Content-Type: application/json');

I suppose problem is somewhere here: 我想问题出在这里:

'<?php echo $this->url('/register', 'do_register')?>', in using quotes. '<?php echo $this->url('/register', 'do_register')?>',使用引号引起来。

Use double and single quotes: 使用双引号和单引号:

"<?php echo $this->url('/register', 'do_register')?>", . "<?php echo $this->url('/register', 'do_register')?>",

It's impossible to receive right suggestion with little description. 很少描述就不可能收到正确的建议。

Y'd better to paste more php & javascript code, with much more context, thing to be simple. 最好粘贴更多的php和javascript代码,并附带更多上下文,这很简单。

And another suggestion, mixed coding is bad. 还有一个建议,混合编码是不好的。 separating the javascript and php with php template such as Smarty. 用Smarty等php模板分隔javascript和php。

var data = $('form#registration-form').serialize();
$.post(
'<?php echo $this->url('/register', 'do_register')?>',
function(data) {
 alert(data);
},
'json'
);

this source file of above code is a php file ? 以上代码的此源文件是php文件?

Debug with firebug to capture weather the ajax request sent or not 使用firebug进行调试以捕获发送或未发送ajax请求的天气

Why use JSON helper?? 为什么要使用JSON助手?

json_decode(string $json);
json_encode(mixed $value); //normally array...

it is built-in in php. 它是内置在PHP中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM