简体   繁体   English

为什么我无法在Ajax中使用POST方法获取参数?

[英]Why can't I get parameters using POST method in ajax?

Here's what I'm trying using ajax: 这是我正在尝试使用ajax的内容:

var x="";
var xxx= setTimeout(myFunc, 7000);
function myFunc(){
    x=document.forms["form1"]["image"].value;
    if(x!=""){
    var xhttp= new XMLHttpRequest();
    xhttp.onreadystatechange=function(){
    if(xhttp.readyState==4 && xhttp.status==200){
        var z= xhttp.responseText;
        alert(z);
        }
    };
       xhttp.open("POST", "test.php", true);
       xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
       xhttp.send("url="+x);
    }
}

Here's test.php: 这是test.php:

<?php
$a= $_POST["url"];
echo $a;
?>

But the alert(z) shows some HTML document, not the URL . 但是alert(z)显示的是一些HTML文档,而不是URL What wrong I'm doing? 我在做什么错? How can I correct it and get parameters from ajax? 我如何纠正它并从ajax获取参数?

Put the following corrections to your js part and test.php file: 将以下更正放入您的js部分和test.php文件中:

  • js part: js部分:

     ... var params = "url="+ encodeURIComponenet(x); xhttp.open("POST", "test.php", true); xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhttp.setRequestHeader("Content-length", params.length); xhttp.send(params); 
  • test.php test.php

     <?php if (isset($_POST["url"]) && !empty($_POST["url"])) { $a = $_POST["url"]; echo $a; } ?> 

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

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