How can I pass form data AND my own variables via jQuery Ajax call?

喜夏-厌秋 提交于 2019-12-11 05:29:02

问题


Here is my working code:

jQuery.ajax({
type: 'post',
url: ajaxurl,
dataType: 'json',
data: jQuery('select[name^="option"], :input[name^="option"]),
success: function (mydata) {
    // do something
}
});

I want to add a variable to be passed back along with the select and textbox option values called 'myVar'. But I don't see it in the parameters when I add it:

var myVar = '123';

jQuery.ajax({
type: 'post',
url: ajaxurl,
dataType: 'json',
data: jQuery('select[name^="option"], :input[name^="option"], myvar='+myVar),
success: function (mydata) {
    // do something
}
});

Am I doing something wrong? Do I need to serialize or encodeURIcomponent or something? Nothing seems to affect it. I still get the select and textbox data, but myVar doesn't come at all in the $_POST side.

Thoughts?


回答1:


Have you tried:

 var myVar = '123';
 jQuery.ajax({
    type: 'post',
    url: ajaxurl,
    dataType: 'json',
    data: jQuery.param(jQuery('select[name^="option"]').val()) + jQuery.param(jQuery('input[name^="option"]').val()) + '&myvar=' + myVar,
    success: function (mydata) {
        // do something
    }
  });

I think you can also use traditional: true instead of param



来源:https://stackoverflow.com/questions/18933833/how-can-i-pass-form-data-and-my-own-variables-via-jquery-ajax-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!