功能jQuery中的Ajax参数参数、功能、jQuery、Ajax

2023-09-10 19:47:47 作者:千殇月

是否有可能把一个函数变成一个参数的jQuery阿贾克斯如下图所示。的dataType和数据被给定为函数。的dataType返回JSON的值,如果返回类型是JSON和文本,如果isJson是假的。

Is it possible to put a function into a parameter for Jquery Ajax like below. dataType and data are given as functions. dataType returns a value of JSON if the returntype is JSON and text if isJson is false.

dataVal和dataVar是含有用于构建数据paramater的参数名称和值阵列。数据的结果:功能将是一个字符串作为

dataVal and dataVar are arrays containing the parameter names and values used to construct the data paramater. The result of the data: function would be a string as:

{dataVar[0]:dataVal[0],dataVar[1]:dataVal[1],.....,}

我得到一个错误,当我尝试这一点,所以,只是想知道,如果这个方法是可行的。

I'm getting an error when I try this, so, just wanted to know if this method was possible.

function getAjaxResponse(page, isJson, dataVar, dataVal, dfd) {
    $.ajax(page, {
        type: 'POST',
        dataType: function () {
            if (isJson == true) {
                return "JSON";
            } else {
                return "text";
            }
        },
        data: function () {
            var dataString = '{';
            for (var i = 0; i < dataVar.length; i++) {
                dataString = dataString + dataVar[i] + ':' + dataVal[i] + ',';
            }
            console.log(dataString);
            return dataString + '}';
        },
        success: function (res) {
            dfd.resolve(res);
        }
    });
}

修改

按答案和注释,所做的更改。更新的功能是如下。这工作:

As per answers and comments, made the changes. The updated function is as below. This works:

function getAjaxResponse(page, isJson, dataVar, dataVal, dfd) {
    $.ajax(page, {
        type: 'POST',
        dataType: isJson ? "JSON" : "text",
        data: function () {
            var dataString ="";
            for (var i = 0; i < dataVar.length; i++) {
                if (i == dataVar.length - 1) {
                    dataString = dataString + dataVar[i] + '=' + dataVal[i];
                } else {
                    dataString = dataString + dataVar[i] + '=' + dataVal[i] + ',';
                }
            }
            return dataString;
        }(),
        success: function (res) {
            dfd.resolve(res);
        }
    });
}

和我原来的问题被回答。但很显然,数据不会被市场接受。

And my original question is answered. But apparently, data is not getting accepted.

数据函数的返回值只是当作参数的名称和jQuery只是增加了一个:像这样的请求结束:

The return value of the data function is just treated as the parameter name and jquery just adds a : to the end of the request like so:

{dataVar[0]:dataVal[0]}:

所以,我的服务器是无法拿起正确的paramater名称。

So, my server is unable to pick up on the proper paramater name.

推荐答案

从手动

数据   类型:PlainObject或字符串

data Type: PlainObject or String

因此​​,没有。

调用函数。使用返回值。

Call the function. Use the return value.

data: function () { ... }();
//                       ^^ call the function