[英]Uncaught SyntaxError: Unexpected token {
Error prompted when execute console.log($obj.longurl)
from the Chrome Developer Console 从Chrome开发者控制台执行
console.log($obj.longurl)
时提示错误
Uncaught SyntaxError: Unexpected token {
$.ajax.complete
L jquery.min.js:19
N
Below is the script I execute from a HTML page and submit a form to call an external PHP file. 以下是我从HTML页面执行并提交表单以调用外部PHP文件的脚本。
Javascript is called from http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js 从http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js调用Javascript
$('#shortener').submit(function(e) {
e.preventDefault();
$('#status').text('');
$.ajax({
cache: false,
type: "POST",
dataType: "json",
data: $('#shortener').serialize(),
url: $('#shortener').attr('action'),
complete: function (XMLHttpRequest, textStatus) {
console.log(XMLHttpRequest);
$obj = JSON.parse(XMLHttpRequest.response);
if ($obj.loginResult == "Passed") {
($('#longurl').val() === "") ? console.log("Empty longurl") : console.log($obj.longurl);
} else {
$('#status').text("Login Failed");
};
}
});
return false;
});
PHP PHP
echo json_encode(array('loginResult' =>'Passed'));
echo json_encode(array('longurl' => BASE_HREF . $shortened_url));
typeof $obj.longurl
is string but don't know why it can be returned to the $('#shortener').val()
, anyone have similar experience and have the solution? typeof
$obj.longurl
是字符串,但不知道为什么可以将其返回给$('#shortener').val()
$obj.longurl
$('#shortener').val()
,任何有类似经验并有解决方案的人?
Your PHP code is producing invalid JSON. 您的PHP代码产生无效的JSON。 You are basically echoing two JSON encoded objects after each other, which overall results in invalid JSON.
您基本上是在互相回显两个JSON编码的对象,这总体上导致无效的JSON。 It will look like:
它看起来像:
{"loginResult": "Passed"} {"longurl": "<some URL>"}
The second {
is the syntax error. 第二个
{
是语法错误。
It should either be an array of objects (although that would be a strange structure) 它应该是一个对象数组(尽管那是一个奇怪的结构)
[{"loginResult": "Passed"}, {"longurl": "<some URL>"}]
or one object 或一个物体
{"loginResult": "Passed", "longurl": "<some URL>"}
Create and encode one array: 创建并编码一个数组:
echo json_encode(array(
'loginResult' => 'Passed',
'longurl' => BASE_HREF . $shortened_url
));
Another problem might be that, at least officially, the jqXHR object passed to the complete callback doesn't have a .response
property. 另一个问题可能是,至少在正式而言,传递给完整回调的jqXHR对象没有
.response
属性。 Since you also already set the dataType: 'json'
option, there is no need for you to parse the response explicitly. 由于您还已经设置了
dataType: 'json'
选项,因此无需显式解析响应。
Here is an improved version of your code: 这是代码的改进版本:
$.ajax({
cache: false,
type: "POST",
dataType: "json",
data: $('#shortener').serialize(),
url: $('#shortener').attr('action'),
}).done(function (data) {
if (data.loginResult == "Passed") {
($('#longurl').val() === "") ? console.log("Empty longurl") : console.log(data.longurl);
} else {
$('#status').text("Login Failed");
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.