发送后$ _REQUEST var为空

时间:2013-01-25 16:35:18

标签: php javascript xmlhttprequest

我正在为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");


        }

3 个答案:

答案 0 :(得分:3)

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

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

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

答案 1 :(得分:-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);
              });
             }
          });
        }

试试这个

答案 2 :(得分:-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    
    }
}



}