jQuery ajax 中没有定义变量

No variables defined in 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);
        });
    });


将其定义为一个函数并将其包装在一个闭包中,并传入上下文。

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, data, function(response) {
    alert('Got this from the server: ' + response);
  });
})(option, note)

jQuery(document).ready(process);

或者,将所有内容移至 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, 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 或类似工具。