我正在使用jQuery.ajax()向REST Web服务发出PUT请求,但看到一些非常奇怪的序列化行为。 (在你说出来之前:是的,我知道并非所有的浏览器都支持PUT--这只是api/framework的一个示例实现,最终不会被浏览器调用,而是由服务器端实现, 。边库确实支持额外的HTTP动词)jQuery编码值与jQuery.ajax数据元素的预期值不同
这里的形式:
<form action="/example/api/artist" method="put" id="update">
First Name: <input type="text" name="firstname" /><br/>
Last Name: <input type="text" name="lastname" /><br/>
Address: <input type="text" name="address" /><br/>
City: <input type="text" name="city" /><br/>
State: <input type="text" name="state" /><br/>
Postal Code: <input type="text" name="postalcode" /><br/>
Email: <input type="text" name="email" /><br/>
Phone: <input type="text" name="phone" /><br/>
Fax: <input type="text" name="fax" /><br/>
Password: <input type="text" name="thepassword" /><br/>
<input type="hidden" name="debug" value="true" />
<input type="submit" value="Update Artist" />
<input type="reset" value="Cancel" id="updateCancel" />
</form>
而且JS:
$("#update").submit(function(e){
e.preventDefault();
var frm = $(this);
$.ajax({
url: frm.attr('action'),
data:{
firstname: $("#update input[name=firstname]").val(),
lastname: $("#update input[name=lastname]").val(),
address: $("#update input[name=address]").val(),
city: $("#update input[name=city]").val(),
state: $("#update input[name=state]").val(),
postalcode: $("#update input[name=postalcode]").val(),
email: $("#update input[name=email]").val(),
phone: $("#update input[name=phone]").val(),
fax: $("#update input[name=fax]").val(),
thepassword: $("#update input[name=thepassword]").val()
},
type: frm.attr('method'),
dataType: "json",
contentType: "application/json",
success: function (data, textStatus, xhr){
console.log(data);
reloadData();
},
error: function (xhr, textStatus, err){
console.log(textStatus);
console.log(err);
}
});
});
当使用Firebug,我看到请求经历,因为这:
姓=奥斯汀&姓氏=韦伯&地址= 25463 +主+街道%2C +套房+ C &城市=伯克利&状态= CA &邮编= 94707-4513 &电子邮件=奥斯汀%40life.com &手机= 555-513-4318 &传真= 510-513-4888 & thepassword = nopolyes
这并不可怕,但最好我宁愿得到%20
而不是+
的空格。我试着包装的每个字段值查找在逃生:
firstname: escape($("#update input[name=firstname]").val())
但是,这使事情变得更糟:
姓=奥斯汀&姓氏=韦伯&地址= 25463%2520Main%2520Street%252C%2520Suite% 2520C &城市=伯克利&状态= CA &邮编= 94707-4513 &电子邮件=奥斯汀%40life.com &手机= 555-513-4318 &传真= 510-513-4888 & thepassword = nopolyes
在这种情况下,该值被转义两次;所以首先将空间编码为%20
,然后将%符号转义为%25
,从而导致空格为%2520
,在地址字段中导致逗号为%252C
。
我在这里做错了什么?
原来这个框架没有正确解码url变量,修正了将+ s正确地解码为空格的问题。 – 2010-06-09 22:10:54