Variable data in ajax call JQUERY

后端 未结 7 1035
有刺的猬
有刺的猬 2020-12-31 14:58

I\'m trying to use variable in AJAX call in jquery but it is not working. move variable contains different values. Please check the following code:

var $move         


        
相关标签:
7条回答
  • 2020-12-31 15:23

    I was looking for something like this. I wanted to have a variable for the key AND a variable for the value.

    let dataPair = {};
    dataPair[dataKey] = dataValue;
    $.ajax({
      url: TheAPIPath,
      data: dataPair,
      method: "GET",
    (etc)
    
    0 讨论(0)
  • 2020-12-31 15:28

    If you want to have a variable-variable in your POST request, you will need to make a seperate JSON object:

    var name = 'next';
    var dataObject = {};
    dataObject[name] = 1;
    
    $.ajax({
       type: "POST",
       url: "somephp.php",
       data: dataObject,
       complete : function() {
         // success!
       }
    });
    
    0 讨论(0)
  • 2020-12-31 15:38

    You can do something like data: $move+"=1"

    0 讨论(0)
  • 2020-12-31 15:40

    It looks like you are trying to use a PHP variable in javascript. You can use .serialize to gather data and pass it to the ajax call. But as for making calls with different named variables for the name of the value pair, you will need to gather that information from the php page you are passing.

    Example:

    $.get("jQueryFunctions.php?action=checkCaptula",$('#resetPasswordDiv :input').serialize()).done(function(data){ ....
    

    While this is a .get instead of a .ajax, it's just shorthand for the .ajax call. The passwordDiv contains HTML inputs with names and id. It gathers the information and passes it to the php page for processing.

    0 讨论(0)
  • 2020-12-31 15:41

    It should be

    $.ajax({
       type: "POST",
       url: "somephp.php",
       data: {"data":$move},
    });
    
    0 讨论(0)
  • 2020-12-31 15:42

    If you want to use the variable as the name of the property, use array notation.

    There are two ways to access object members: dot notation and bracket notation (a.k.a. subscript operator).

    Your code with array notation:

    var $move = 'next';
    var data = {};
    data[$move] = 1;
    
    $.ajax({
       type: "POST",
       url: "somephp.php",
       data: data,
    });
    

    The example on jsfiddle (the post obviously doesn't work, so check the console to see what gets posted.)

    0 讨论(0)
提交回复
热议问题