如何发送JSON但在应对与AJAX / JQuery的预期纯文本? [英] How do I send JSON but expect plain-text in response with AJAX / JQuery?
问题描述
在下面的脚本,我张贴JSON格式到服务器的数据,但响应发送回纯文本。
In the following script, I post data in JSON format to the server, but the response is sent back in plain-text.
var regCredentials = {
"username": creds.username,
"password": creds.password,
"fname": creds.fname,
"lname": creds.lname
};
request = $.ajax({
url: "internet.com/register",
type: "POST",
crossDomain: true,
data: regCredentials,
dataType: "json";
request.always(function (data) {
console.log("Response: " + data);
postResponse(data);
};
});
由于该函数需要JSON回来,追加到返回的数据。它很可能已经分析过,这不出于某种原因抛出异常。
Because the function expects JSON back, a "
is appended to the returned data. It's probably parsed too, which doesn't throw an error for some reason.
我怎么能写一个jQuery AJAX后接受纯文本格式的反应呢?
编辑:
我的困惑我认识,是我觉得数据
确定传出和传入期望的格式,而不是仅仅传入。嗯,这没有太大的意义不是吗?感谢您的回答!
My confusion I realize, is that I thought data
determined the outgoing and incoming expected format rather than just incoming. Well that doesn't make much sense does it? Thanks for the answer!
推荐答案
在的dataType
参数是用来设置预期的反应类型。在你的情况下,将其设置为文本
。这不影响其以任何方式发送的信息。当你发送一个POST请求,该信息将被放置在请求标题。如果这是一个GET,它会被序列化到一个字符串,并追加到查询字符串的URL。
The dataType
parameter is used to set the expected response type. In your case, set it to text
. This does not affect the information which is sent in any way. As you are sending a POST request, the information will be placed in the requests' header. If it was a GET, it would be serialised to a string and appended to the URL in the querystring.
您身边的处理函数的语法是有点过了。试试这个:
Your syntax around the handler function was a little off too. Try this:
var regCredentials = {
"username": creds.username,
"password": creds.password,
"fname": creds.fname,
"lname": creds.lname
};
request = $.ajax({
url: "internet.com/register",
type: "POST",
crossDomain: true,
data: regCredentials,
dataType: "text",
success: function (data) {
console.log("Response: " + data);
postResponse(data);
}
});
这篇关于如何发送JSON但在应对与AJAX / JQuery的预期纯文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!