0

所以我想创建一个“POST”到另一个页面。我想像下面那样做......

$.ajax({

    type: "POST",
    url: "maintain.aspx",
    data: { key1:value1, key2:value2, key3:value3 },
    success: function(msg){
        alert("Done!");
    }

});

问题是我没有变量形式的数据。相反,我以格式如下的字符串提供数据......

&myvar=1&thisguy=dave&thatguy=martin

如何从该字符串中获取键/值信息到data: {}ajax 调用部分?谢谢!

4

3 回答 3

4

data属性可以是您拥有的对象,也可以是查询字符串。因此,您可以简单地按原样使用它。(尽管您可能需要去掉前导&)。

$.ajax({
    type: "POST",
    url: "maintain.aspx",
    data: "myvar=1&thisguy=dave&thatguy=martin",
    success: function(msg){
        alert("Done!");
    }
});
于 2013-01-12T02:08:33.647 回答
0

试试这个

var str = "&myvar=1&thisguy=dave&thatguy=martin";

var params = str.split('&');

var objData = {};
for (var i = 0; i < params.length; i++) {
  if (params[i] !== '') {
    var attrs = params[i].split('=');
    if (attrs.length) {
      objData[attrs[0]] = attrs[1];
    }
  }
}

$.ajax({
  type: "POST",
  url: "maintain.aspx",
  data: objData,
  success: function (msg) {
    alert("Done!");
  }

});
console.log(objData)

检查小提琴

于 2013-01-12T02:11:08.803 回答
-1

对困惑感到抱歉。这是一个例子:

var url = "?param1=123&param2=222&param3=aaaa";
var json = {param1: " + getQueryString(url, param1)  + ", param2: " + getQueryString(url, param2)  + "}

function getQueryString(url, param){
        var currentURL ="";
        currentURL = url;
        var separar = currentURL.split("&");
        var value = "";
        for (i = 0; i < separar.length; i++) {
            var separarValue = separar[i].split("=");
            if (separarValue[0] == a) {

                value = separarValue[1];
                break;
            }
        }
        return value;
    }
于 2013-01-12T02:35:11.720 回答