我试图使用Dojo发布到我的服务器。服务器返回一个JSON响应(我已经调试过它并知道它返回一个合理的值),但是当它返回时,我只是在Javascript控制台中出现'语法错误'。有任何想法吗?xhr.post没有得到JSON响应
function submitStatusUpdate() {
dojo.xhr.post({
form:"statusUpdateForm",
handleAs: "json",
load: function(data){
alert('Saved with id ' + data.id);
},
error: function(err, ioArgs){
// again, ioArgs is useful, but not in simple cases
alert('An error occurred');
console.error(err); // display the error
}
});
}
我也试着像这样
function submitStatusUpdate() {
var posted = dojo.xhr.post({
form:"statusUpdateForm",
load: function(data){
},
error: function(err, ioArgs){
// again, ioArgs is useful, but not in simple cases
console.error(err); // display the error
}
});
posted.then(function(response){
alert('returned ' + response);
});
}
但是被我警戒打印出来的反应似乎只是为我的整个页面的HTML。我期待着一个JSON对象。我努力寻找一个简单的例子,告诉我如何提交表单,然后有一个读取响应的回调函数。
感谢
编辑(感谢Richard为指导)
这是工作版本。
<script language="Javascript">
dojo.require("dijit.form.Button");
dojo.require("dijit.form.TextBox");
dojo.require("dijit.form.CheckBox");
function sendForm(){
var form = dojo.byId("myform");
dojo.connect(form, "onsubmit", function(event){
// Stop the submit event since we want to control form submission.
dojo.stopEvent(event);
// The parameters to pass to xhrPost, the form, how to handle it, and the callbacks.
// Note that there isn't a url passed. xhrPost will extract the url to call from the form's
//'action' attribute. You could also leave off the action attribute and set the url of the xhrPost object
// either should work.
var xhrArgs = {
form: dojo.byId("myform"),
load: function(data){
// As long as the server is correctly returning JSON responses, the alert will
// print out 'Form posted. ' and then the properties and values of the JSON object returned
alert("Form posted." + data);
},
error: function(error){
// We'll 404 in the demo, but that's okay. We don't have a 'postIt' service on the
// docs server.
alert("error");
}
}
// Call the asynchronous xhrPost
alert("Form being sent...");
var deferred = dojo.xhrPost(xhrArgs);
});
}
dojo.ready(sendForm);
</script>
这是(种)什么我的形式看起来像。无论如何,这将工作(我的真实形式要大得多)。有趣的是,我不得不改变我的正常[输入类型=“提交” ...]标记为[按钮...]得到它才能正常工作
<form method="post" id="theform" action="postIt">
<input value="Some text" name="formInput" type="text"/>
<input name="checkboxInput" type="checkbox"/>
<button id="submitButton" type="submit">Send it!</button>
</form>
啊,我刚刚发现了我正在做的一些愚蠢的事情。我在表单中的提交按钮上放置了一个onClick事件,因此它可能会提交两次。表单的动作(url)是http:// myserver/myapp/statusupdates/submit虽然。这是一个Java应用程序,我可以在其中插入一个断点并看到它正在被调用,但我现在想知道我是否全部错了。我认为上述功能在表单提交时被调用。不要以为你知道提交表单然后阅读JSON响应的好例子?谢谢 – Richard 2012-03-17 12:06:07
感谢那个例子,它现在开始有意义。我试试吧,欢呼吧 – Richard 2012-03-17 12:56:31
终于有工作了!你是对的,我的服务器配置不是很正确:我使用Spring MVC,但是我没有把杰克逊当成一个Maven依赖项。一旦我添加了,我的方法确实将JSON返回到“加载”函数。我使用了您发布的示例(链接中的第一个示例),现在它工作正常。如果您为我的问题(而不是评论)创建答案,我会将其标记为正确,以便获得信用。感谢一百万,这一直驱使我慢慢疯狂:) – Richard 2012-03-17 17:47:02