doujiushi9007 2017-03-31 21:51
浏览 59
已采纳

PHP文件未收到JavaScript Ajax URL“post”数据

I was wondering if you'd be able to help me with this issue please?

I'm looking to pass variable length HTML (or any data in fact) to a PHP file via POST in a JavaScript AJAX method.

I want to use JavaScript for my entire project so I can cut my teeth on it - I know a lot of solutions are provided in jQuery for AJAX but hopefully you can help me via vanilla JavaScript. :)

I pass the data in the 'prepare' variable in the URL as follows:

ajax("doit.php?preparedOutput=" + prepare);

The AJAX function:

function ajax(queryURL) {
alert(queryURL); // check the right data is being sent
var xhttp = new XMLHttpRequest();

xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
        alert(xhttp.responseText);
        output2.value = xhttp.responseText;
        result.innerHTML = "<h3>your HTML</h3>" + xhttp.responseText;
    }
}
//var encodedQueryURL = encodeURIComponent(queryURL);
xhttp.open("POST", "doit.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//alert(encodedQueryURL); // check the right encoded data is being sent
xhttp.send(queryURL);
}

The alerts show me what data is supposedly being sent, whether encoded or not. All seems fine. But the response I get back from the PHP is... nothing.

<?php
$preparedOutput = $_POST['preparedOutput'];

echo $preparedOutput;
?>

Even if I use isset($preparedOutput) in an if/else block, else is triggered. Nothing's getting through. Not even if I try to pass simple numbers or letters without spaces, aside from HTML. Nothing's getting to the PHP file apparently.

I've been toying with the setRequestHeader, trying all sorts, namely "text/html" etc. Nothing changes the outcome. I feel I'm missing a key piece of the puzzle here!

If it helps, my environment is PHP enabled in IIS7 using FastCGI - if this makes any difference. PHP works, I previously had the PHP script embedded within the same page and it returned the entire page's HTML rather than the HTML in the preparedOutput variable, which is why I shifted it to its own file.

Thanks

  • 写回答

1条回答 默认 最新

  • duanchanguo7603 2017-03-31 21:54
    关注

    That's because you doubled the url string. Take a look:

    You called it by

    ajax("doit.php?preparedOutput=" + prepare);
    

    and the url you use in open is "doit.php"

    so you basically call something like http://whatever/doit/?doit.php?preparedOutput=" + prepare.

    Change to:

    ajax("preparedOutput=" + prepare);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题