简体   繁体   中英

How to use a JSON-like JQuery function?

How can I use JSON-like variable in my function like this?

$.ajax({
      type:"POST",
      -->data:{this_var:this_value}
     });

Use JSON.stringify() to create JSON object.

$.ajax({
        type: "POST",
        url: urlAction,
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify({variable1: value1, variable2: value2})
      });

Your code:

$.ajax({
      type:"POST",
      -->data:{this_var:this_value}
     });

Then to use the object as you mentioned would be:

var myObj = {this_var:this_value};
myObj.this_var();

That is if this_var is a function. Otherwise the value can be consumed such as:

var myObj = {this_var:this_value};
var myVal = myObj.this_var;

You may also need to pass the data in as a string and then parse it as JSON after getting the string from the ajax call.

var myObj = JSON.parse(data);
var myVal = myObj.this_var(); // if this is a function

Try this

formData = {
    param1: $("#param1").val(),
    param2: $("#param2").val()
}
$.ajax({
    type: "POST",
    url: "http://example.com/create.php",
    data: formData,
    dataType: "json",
    success: function(data) {
        alert("Add success");
    },
    error: function() {
        alert("Add failure");
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM