繁体   English   中英

参数化ajax请求体

[英]Parametric ajax request body

我希望能够插入或插入 ajax 请求正文的数据部分。 假设我有一个这样的 ajax 主体;

"ajax": {
            "url": `/${controllerName}/${actionName}`,
            "type": "POST",
            "data": {example : values},
            "datatype": "json"
        }

我希望能够有条件地添加或删除此 ajax 正文的data部分。 我试过这样的事情;

"ajax": {
            "url": `/${controllerName}/${actionName}`,
            "type": "POST",
            exampleCondition == true ? ("data": {example : values}) : "",
            "datatype": "json"
        }

但它显然不起作用。 我想不出如何做到这一点。

提前致谢。

您可以使用扩展语法将对象扩展为其属性。 通过将此语法与三元运算符相结合,您可以有条件地以简洁的方式向对象添加新属性。

例如,有一个错误的条件:

 const exampleCondition = false; const ajax = { url: "http://test.com", type: "POST", datatype: "json", ...(exampleCondition ? {data: {example : 'example'}} : {}) }; console.log(ajax);

以及一个具有真实条件的示例:

 const exampleCondition = true; const ajax = { url: "http://test.com", type: "POST", datatype: "json", ...(exampleCondition ? {data: {example : 'example'}} : {}) }; console.log(ajax);

您可以简单地使用 javascript 对象之外的条件代码来做到这一点。

var ajax = {
  "url": `/${controllerName}/${actionName}`,
  "type": "POST",
  "datatype": "json"
}

if(exampleCondition == true) {
    ajax.data = {example: values2}
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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