jQuery ajax 中没有定义变量

问题描述

我通常使用 javascript ajax,一切正常,但 wordpress 需要我不熟悉的 jquery ajax。

为什么下面代码中描述的变量没有定义?


var option = "'USER_ID': 'my id is 32',"
var note = "'this is my first note'";

    jQuery(document).ready(function($) {

        var data = {
            'action': 'my_action',option   //this does not work. <--- WHAT DO YOU MEAN DOES NOT WORK?
            'USER_NOTE': note  //this does not work. <--- WHAT DO YOU MEAN DOES NOT WORK?
            
        };

        // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
        jQuery.post(ajaxurl,data,function(response) {
            alert('Got this from the server: ' + response);
        });
    });


解决方法

这是因为您的 data json 对象没有正确定义。您需要将选项定义更改为有效的 json 对象:

var option = "'USER_ID': 'my id is 32',"

var option = {'USER_ID': 'my id is 32'}

并以不同的方式添加它,以便正确合并:

var data = {
        'action': 'my_action',...option,'USER_NOTE': note           
        
    };

那应该可以解决您的问题。

,

这是带有您问题的代码笔:https://codepen.io/geoidesic/pen/wvoEdeN

代码如下:

var option = "'USER_ID': 'my id is 32',";
var USER_ID = 'my id is 32';
var note = "'this is my first note'";


jQuery(document).ready(function($) {
  console.log(option); // proves that option is in scope
  console.log(note); // proves that option is in scope
  var data = {
            'action': 'my_action',USER_ID,'USER_NOTE': note
        };
  console.log(data); // proves that data is working

  jQuery.post('https://jsonplaceholder.typicode.com/posts',data,(response) => {
    console.log('response: ',response);
  })
});

如果您查看控制台。可以看到任何未定义的变量都没有问题。如果您查看网络选项卡,您可以看到 POST 请求已发送。

这也应该作为一个例子,说明如何更好地以人们可以实际帮助您的方式来表述您的问题,即使用 CodePen 或类似工具。

,

或者,将所有内容移入 jQuery.ready


  jQuery(document).ready(function($) {
    
    var option = "'USER_ID': 'my id is 32',"
    var note = "this is my first note";

    var data = {
        'action': 'my_action',option,'USER_NOTE': note           
        
    };

    jQuery.post(ajaxurl,function(response) {
        alert('Got this from the server: ' + response);
    });
  });

,

将其定义为函数并将其包装在传递上下文的闭包中。

var option = "'USER_ID': 'my id is 32',"
var note = "this is my first note";
const process = (function() {
  const data = {
    'action': 'my_action',option
    'USER_NOTE': note
  }
  jQuery.post(ajaxurl,function(response) {
    alert('Got this from the server: ' + response);
  });
})(option,note)

jQuery(document).ready(process);

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...