PHP 中的 JSON 中的单引号导致问题
注意:这是一个完全不同的问题,直到我意识到问题真正出在哪里。
我当前的问题是我正在尝试从 PHP 输出一些 JSON 供 jQuery 使用。我正在做这个跨域,所以我使用“JSONP”。我已将问题范围缩小到 JSON 中存在单引号,因此当我使用回调函数输出时,我最终会得到太多单引号。
我尝试在 PHP 中调用 str_replace("'","\'",$value)
,它似乎在我的 JSON 中输出为 \\'
而不是 \'
显然 jQuery 无法读取(尽管在线 JSON 验证器说 JSON 是有效的。
所以我需要知道的是如何在 PHP 内的字符串中仅获取单个斜杠而不是 2 个斜杠。
NOTE: this was a completely different question until I realized where the problem really was.
My current issue is that I am trying to output some JSON from PHP for use by jQuery. I am doing this cross-domain so I am using "JSONP". I have narrowed the problem down to the fact that there are single quotes in my JSON so when I output with the callback function I end up getting too many single quotes.
I have tried calling str_replace("'","\'",$value)
in PHP and it seems to output as \\'
in my JSON rather than \'
which is apparently not readable by jQuery (though online JSON validators say the JSON is valid.
So what I need to know is how to get only a single slash in my string inside of PHP rather than 2 slashes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我收集到的是:
jQuery 使用
_
作为 JSONP 请求的回调参数。它会自动附加?_=jQuery
基本上告诉服务器在返回时调用这个唯一的函数名称。因此,截至最近(我想说的是去年).ajax
负责为您创建一个回调函数,然后将其“重新路由”到您在其中指定的函数success
属性。另外,您的 PHP 代码正在使用
$_GET['callback']
,而现在应该使用$_GET['_']
(为了与 jQuery 保持一致)以及发送的内容)。“jQuery 未被调用”只是 jQuery 通知您预期的回调未包含在响应中,并且它希望确保它被调用。
简短的回答(据我所知)引用
$_GET['_']
而不是$_GET['callback']
来满足 jQuery。What I'm gathering is this:
jQuery uses
_
as a callback parameter to JSONP requests. It will automatically append?_=jQuery<random_numbers>
basically telling the server to call this unique function name when it returns. As such, as of recently (within the last year I want to say).ajax
takes care of making a callback function for you, then kind of "re-routes" it to a function you specify within thesuccess
property.Also, your PHP code is using
$_GET['callback']
when it now should be using$_GET['_']
(to stay more in-line with jQuery and what it's sending).The "jQuery was not called" is just jQuery notifying you that anticipated callback wasn't included in the response, and it was looking to make sure it was getting called.
Short answer (as I see it) reference
$_GET['_']
instead of$_GET['callback']
to satisfy jQuery.尝试在您的 PHP 中使用它:
问候。
try to use this in your PHP:
Regards.