如何在jQuery Ajax中同时发送动态键和值?(复制)

时间:2022-12-08 20:02:04

This question already has an answer here:

这个问题已经有了答案:

I want to send both the key and value to be dynamic(and the key is dynamic like coming from user input). Then how to send the request. I want something like this:

我希望将键和值都发送为动态(键是动态的,就像来自用户输入一样)。然后如何发送请求。我想要这样的东西:

var requestString;

if(something)
   requestString = "something";
else
   requestString= "else";

    jQuery.ajax({
                        url: handlerUrl,
                        dataType: "json",
                        data: {
                            requestString: request.term
                        }
                    });

Here requestString is a variable and dynamically set. But for current code. the key is itself becoming "requestString" which was ought to be dynamic. How to do this?

这里requestString是一个动态设置的变量,但是对于当前代码。键本身变成了“requestString”,应该是动态的。如何做到这一点呢?

2 个解决方案

#1


3  

Use

使用

jQuery.ajax({
           url: handlerUrl,
           dataType: "json",
           data: requestString + '=' + request.term
      });

#2


2  

create an object, push the dynamically generated key and value to it.. and pass that object as data in ajax..

创建一个对象,将动态生成的键和值推给它。并将该对象作为ajax中的数据传递。

try this

试试这个

var requestString ;
 .....
dataString={};
dataString[requestString]=request.term

jQuery.ajax({
               url: handlerUrl,
               dataType: "json",
               data: dataString
          });

#1


3  

Use

使用

jQuery.ajax({
           url: handlerUrl,
           dataType: "json",
           data: requestString + '=' + request.term
      });

#2


2  

create an object, push the dynamically generated key and value to it.. and pass that object as data in ajax..

创建一个对象,将动态生成的键和值推给它。并将该对象作为ajax中的数据传递。

try this

试试这个

var requestString ;
 .....
dataString={};
dataString[requestString]=request.term

jQuery.ajax({
               url: handlerUrl,
               dataType: "json",
               data: dataString
          });