JavaScript字符串对象被拆分为jQuery.post上的数组

JavaScript String object is being split into an array on jQuery.post

本文关键字:post 数组 jQuery 字符串 对象 拆分 JavaScript      更新时间:2023-09-26

我正在使用jQuery进行ajax调用—其中许多调用都工作得很好,但是我刚刚遇到了一个奇怪的问题,试图将字符串发送到服务器。我把代码缩小到这样:

var x = new String('updateGroup');
var y = 'updateGroup';
$.post('page.aspx', {
    f: x,
    f2: y
}, function(data) {
});

当它到达服务器时,请求变量如下:

Request["f"]          null          string
Request["f2"]         "updateGroup" string
Request.Form.AllKeys  {string[12]}  string[]
  [0]                 "f[0]"        string
  [1]                 "f[1]"        string
  [2]                 "f[2]"        string
  [3]                 "f[3]"        string
  [4]                 "f[4]"        string
  [5]                 "f[5]"        string
  [6]                 "f[6]"        string
  [7]                 "f[7]"        string
  [8]                 "f[8]"        string
  [9]                 "f[9]"        string
  [10]                "f[10]"       string
  [11]                "f2"          string

其中Request["f[0]"]包含"u"

谁能解释一下为什么会这样?

如果你抛开所有细节,在你的例子中执行的是:

  • jQuery.post
  • 调用jQuery.ajax内部做ajax
  • 在内部调用jQuery.param来构建查询字符串
关键是new String不是一个原语字符串,而是一个字符串对象,并且在jQuery.ajax (typeof new String("foo") === "object",而不是"string")中将通过的以下检查:
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
    s.data = jQuery.param( s.data, s.traditional );
}

jQuery.param正在执行如下命令:

for ( var prefix in a ) {
    buildParams( prefix, a[ prefix ], traditional, add );
}

这意味着它对字符串执行for in循环,这确实将每个字符单独放在查询字符串中。

你可以用这个测试用例检查这个行为:

var x = new String("abc");
for(var i in x) {
    console.log(i, x[i]);
}
// 0  "a"
// 1  "b"
// 2  "c"

当你使用new String时,你创建了一个字符串对象而不是字符串本身,如果你在浏览器中运行这个,你会看到它们是一个对象和一个字符串:

console.log(typeof new String("hello"));
console.log(typeof "hello");

更多信息在这里(包括为什么你可以一个数组的字符发送到服务器):http://www.devguru.com/technologies/ecmascript/quickref/string.html

JavaScript区分字面值字符串和字符串类型的对象。
我怀疑当jQuery post方法检查您发送给它的数据对象时,它会检查typeof每个值是否为string。如果是,它的任务就完成了。如果它找到一个对象(String就是对象),它就会遍历它——这就是为什么你会得到一个字符数组。

如果你有一个String对象,你可以使用String.valueOf()来获取原始值

你不应该在javascript中创建这样的字符串,这被认为是一个不好的做法:

 var x = new String('updateGroup');

但总是这样

 var x = 'updateGroup';

,因为在第一种情况下,您创建一个对象,只有在第二种情况下,您创建一个字符串。数组也是一样,总是使用

 var array = [];