< script></script>与JSON响应一起发送的代码 [英] <script></script> code sent along with json response

查看:178
本文介绍了< script></script>与JSON响应一起发送的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Jquery对PHP页面进行AJAX调用,该页面使用json_encode函数输出JSON. 此PHP页面还包含javascript代码,该代码与JSON代码一起发送,从而导致JSON解析错误. 有办法防止这种情况吗? 非常感谢您的支持.

I'm using Jquery to make an AJAX call to a PHP page which outputs JSON with the json_encode function. This PHP page contains javascript code as well, which is sent along with the JSON code, resulting in a JSON parse error. Is there a way to prevent this? Many thanks for your support.

PHP页面:

<script type="text/javascript">
//javascript needed on this page
</script>

//json output
$data = array('one'=> 'hello', 'two' => 'world');
echo json_encode($data);

推荐答案

没有更多细节很难知道,但是我认为您的PHP页面具有不同的角色,其中之一是由于ajax请求而打印JSON的. 我认为您应该只为该角色打印JSON,为其余角色打印Javascript和Html,使用排他参数区分HTTP响应的类型,使用Accept HTTP标头和Content-Type或使用不同的http方法(GET,POST, ...)出于您的不同目的(为此您最后可以阅读REST).

Without more detail is difficult to know, but I think your PHP page has different roles, one of them to print JSON as a result of an ajax request. I think you should print JSON only for this role, and Javascript and Html for the rest of roles, differentiating the type of http response using exclusive parameters, playing with Accept http header and Content-Type or using different http methods (GET, POST, ...) for your different purposes (for this last you can read about REST).

这篇关于&lt; script&gt;&lt;/script&gt;与JSON响应一起发送的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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