0

我正在为 wp 做一个 ajax 函数。但我总是得到响应 0。我看到了文件 admin-ajax.php 的代码并看到了这个:

if ( empty( $_REQUEST['action'] ) )
    die( '0' );

这是我的 js 函数 ajax。

function fnc(){

            var ajax=new  XMLHttpRequest();
            ajax.open("POST", "<?php echo get_site_url(); ?>/wp-admin/admin-ajax.php");



                ajax.onreadystatechange= function(){
                    if (ajax.readyState === 4) {
                        if (ajax.status === 200) {
                            alert(ajax.responseType);
                            alert(ajax.responseText);
                        } else {
                            alert('There was a problem with the request.');
                        }
                    }
                }
                ajax.send("action=some_function");


        }
4

3 回答 3

3

为了将send字符串用作表单数据,您可能需要添加以下标题:

ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

没有这个,PHP 不会将原始 POST 数据转换为$_POST/$_REQUEST变量。

于 2013-01-25T16:43:07.600 回答
-1
$.ajax({
          type:'POST',
          url:"<?php echo get_site_url(); ?>/wp-admin/admin-ajax.php",
          data:'', //  what you want to post
          success:function(data){
                    alert(data);
              });
             }
          });
        }

尝试这个

于 2013-01-25T16:40:46.093 回答
-1
If you want to use javascript and XMLHttpRequest this is the full way to do that :)


function ajax_post(){
// Create our XMLHttpRequest object
var ajax=new  XMLHttpRequest();

// Create data to send to our PHP file

var url = "xyz.php";
var fn = document.getElementById("a").value;
var ln = document.getElementById("b").value;
var variable = fn+" hello "+ln;
hr.open("POST", url, true);


// Set content type header  for sending url encoded variables

ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

// Get the onreadystatechange event for the XMLHttpRequest
ajax.onreadystatechange = function() {
    if(ajax.readyState == 4 && ajax.status == 200) {
        var return_data = ajax.responseText;
            alert(ajax.return_data);
            // Send the data to PHP now... and wait for response to update the status div
           ajax.send(variable); // Actually execute the request    
    }
}



}
于 2013-01-25T16:55:17.430 回答