运行node.js文件时出现语法错误

时间:2012-11-16 05:01:50

标签: javascript ajax node.js syntax-error

我正在使用Editinplace功能,在运行时我在chrome控制台上遇到此错误Uncaught SyntaxError: Unexpected token <我正在使用node.js代码段执行此操作,如下所示

case '/':
res.writeHead(302,{'location':'http://localhost/editinplace/index.html'});
res.end();
break;
case '/save':
console.log("called");

    console.log("Inside called");
    res.write('_testcb(\'{"message": "Hello world!"}\')');
res.writeHead(302,{'location':'http://localhost/editinplace/save.html'});

res.end();
break;

index.html的代码如下

<script type="text/javascript">
$(document).ready(function(){
setClickable();
});
function setClickable() {
$('#editInPlace').click(function() {
var textarea = '<div><textarea rows="10" cols="60">'+$(this).html()+'</textarea>';
var button = '<div><input type="button" value="SAVE" class="saveButton" /> OR <input type="button" value="CANCEL"class="cancelButton" /></div></div>';
var revert = $(this).html();
$(this).after(textarea+button).remove();
$('.saveButton').click(function(){saveChanges(this, false);});
$('.cancelButton').click(function(){saveChanges(this, revert);});
})
.mouseover(function() {
$(this).addClass("editable");
})
.mouseout(function() {
$(this).removeClass("editable");
});
};//end of function setClickable
function saveChanges(obj, cancel) {
if(!cancel) {
var t = $(obj).parent().siblings(0).val();
var data=t;
 $.ajax({
        url: 'http://localhost:9090/save',
        type:"GET",
        dataType: "jsonp",
        jsonpCallback: "_testcb",
        cache: true,
        timeout: 1000,
        data:{data:JSON.stringify(data)},
        success: function(data) {
        },
        error: function(jqXHR, textStatus, errorThrown) {
        }
    });
}
else {
var t = cancel;
}
$(obj).parent().parent().after('<div id="editInPlace">'+t+'</div>').remove() ;
}
</script>
</head>
<body>
<div id="editInPlace">Nilesh</div>
</body>

save.html是一个用<pre>标签括起来的简单文字。错误显示在save.html第1行。谢谢您的努力。

1 个答案:

答案 0 :(得分:3)

好的,所以这是发生的事情:

  • 浏览器加载index.html
  • 用户编辑该字段并点击保存
  • saveChanges/save
  • 发出AJAX GET请求
  • 您的服务器代码发送带有302状态代码和jsonp正文
  • 的HTTP响应
  • 我认为浏览器透明地处理302状态代码并忽略正文
  • 因此,您的jquery代码期待来自/save的响应正文的javascript,但它确实从/save.html获取了HTML。这就是语法错误发生的地方,当jquery尝试将该HTML评估为javascript时,因为你告诉它dataTypejsonp

另见this question about browsers handling redirects automatically

解决方案是您需要发送200响应代码,以便jquery可以执行jsonp操作,然后您可以根据需要将window.location更改为/save.html

相关问题