我正在尝试使用Dojo发布到我的服务器。服务器正在返回一个JSON响应(我已经调试它并知道它返回一个合理的值)但是我只是在它返回时在Javascript控制台中得到一个'语法错误'。有什么想法吗?
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对象。我很难找到一个简单的例子来告诉我如何提交表单,然后有一个回调函数来读取响应。
由于
编辑(感谢理查德的指导)
这是工作版本。
<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>
这是我的表格的样子。无论如何这都会起作用(我的真实形式要大得多)。有趣的是,我不得不将我的正常[input type =“submit”...]标签更改为[button ...]以使其正常工作
<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>
答案 0 :(得分:1)
解析XMLHttpRequest回复时的JavaScript语法错误通常表示来自服务器的无效数据。我最喜欢的监控XMLHttpRequest流量的工具是Firebug。它解析JSON,所以如果有什么不对的话,你马上就会知道。
一旦确定服务器的JSON数据有效,请查看以下example from the Dojo documentation。我认为它会做你想做的事情。