Formatting dynamically built parameter string to pass with jquery ajax in data

佐手、 提交于 2020-01-06 19:36:05

问题


I would like to pass data from a dynamically built form via ajax to a php script, but have trouble finding the correct syntax for the parameter string format. There's a couple of fixed parameters and some are added dynamically, keys and values of the latter may change.

I've tried to build the parameter list as a concatenation of strings as below:

...
var dataVars = '{fctSelect: 2, strat: strat, ' + gbl.dataVariables + '}';

...

$j.ajax({
    url: "ajax/script.php",
    type: "POST",
    data: dataVars,
...

gbl.dataVariables is formatted as follows : 'field1: value1, field2: value2, field3, value3'

The resulting string to go into data "looks right" in console.log, but in the post tab of the console once the field validated, it appears like this:

{fctSelect: 2, strat: strat, ...

instead of:

fctSelect: 2
strat: 1
...

meaning that the parameters are not parsed. Could someone please point me to where I went wrong?


回答1:


Darin Dimitrov's solution is probably the way to go for you, I'll just give you an alternative. If you collect your form's fields and their values through serialize(), you can simply append your static data like this:

var dataVars = $('form').serialize(),
    dataVars += dataVars.length > 0 && '&'; // in case there are no form fields
    dataVars += 'fctSelect=2&strat=somevalue';

$j.ajax({
    url: 'ajax/script.php',
    type: 'POST',
    data: dataVars,
    success: function() {}
});



回答2:


I would recommend you an alternative approach than string concatenations:

var dataVars = {};

// add some static values
dataVars['fctSelect'] = 2;
dataVars['strat'] = 'some value';

// now add some dynamic values
for (var i = 0; i < 10; i++) {
    dataVars['field' + i] = i;
}

// send the data as a JSON encoded request
$j.ajax({
    url: 'ajax/script.php',
    type: 'POST',
    data: JSON.stringify(dataVars),
    contentType: 'application/json',
...

and then inside your script.php:

$data = json_decode(file_get_contents("php://input"));


来源:https://stackoverflow.com/questions/12365846/formatting-dynamically-built-parameter-string-to-pass-with-jquery-ajax-in-data

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