2017-03-09 67 views
-1

我的主页上有一个简单的表单,表示POST是随机生成的URL的输入(由$random创建),然后在新选项卡中打开它。这种随机URL运行脚本run.php无法使用PHP访问AJAX数据

<form action="/run.php" method="POST" target="_blank"> 
    <input type="hidden" id="idgen" name="idgen" value="<?php echo $random ?>"> 
    <input type="text" name="userinput" id="userinput"> 
    <button type="submit" onclick="calcResult();">Go!</button> 
</form> 

我也有使用该userinput数据计算结果的网页JavaScript函数。这个结果是(应该是)POST'发送到表单发送到的相同的随机生成的网址。

function calcResult() { 
    var userinput = document.getElementById('userinput').value; 
    var randomid = document.getElementById('idgen').value; 

    // various functions 

    $.ajax({ 
      type: "POST", 
      url: 'http://example.com/' + randomid, // same random url 
      data: {result: "Hello"} 
    }); 

我再加入<?php echo $_POST['result']; ?>run.php文件

如果我打开Chrome开发工具的“网络”选项卡(XHR)并提交表单(窗体打开运行run.php随机URL) ,那么这个AJAX POST does似乎工作(它发送到与表单相同的随机链接。该随机url的'响应'选项卡显示run.php源代码,甚至用AJAX结果"Hello"替换<?php echo $_POST['result']; ?>

因此,它在开发人员工具中成功工作,但它在实际的随机url网页("Hello"没有显示在实际网页中,不像在开发人员工具中)工作。

我现在完全失去了什么可能阻止我访问网页中的AJAX结果。

+2

'

'将数据发送到'run.php',而JavaScript函数正在对'随机文件可能不存在的所有文件进行AJAX调用。你究竟想达到什么目的? – tyteen4a03

+0

当你提交一个表单时,浏览器打开'action'属性指定的页面 - 在这种情况发生之前post请求不会完成 - 事实上,它可能永远不会启动 –

+0

@ tyteen4a03表单将数据发送到'run。然后(使用htaccess规则和PHP代码)发送到一个随机的url example.com/run.php ---> example.com/abcxyz(即运行run.php脚本)'AJAX调用我试图访问与表单数据相同的随机网址上的AJAX数据 – Pebble

回答

0

我认为没有任何东西出来,因为没有回调函数,你可能只是重新加载页面。我想你应该这样做:

function calcResult(e) { 
    e.preventDefault(); 

    var userinput = document.getElementById('userinput').value; 
    var randomid = document.getElementById('idgen').value; 

    // various functions 

    $.ajax({ 
     type: "POST", 
     url: 'http://example.com/' + randomid, // same random url 
     data: {result: "Hello"}, 
     success: function(response){ 
     // callback - do what you wanna do 
     alert(response); 
     }, 
    }); 
} 

更新 -

考虑到要更改的页面,并在run.php同时使用userinput和randomid,你可以在JS做到这一点:

function calcResult(e) { 
    e.preventDefault(); 

    var userinput = document.getElementById('userinput').value; 
    var randomid = document.getElementById('idgen').value; 

    // various functions 

    window.location.href = "http://example.com/run.php?randomid=" + randomid + "userinput=" + userinput; 

} 

然后,在run.php:

<?php 

    if(isset($_GET) { 

    $randomid = $_GET['randomid']; 
    $userinput = $_GET['userinput']; 

    // do what you want with both variables and return $result 

    echo $result; 

    } 

?> 

为你的作品?

+0

我原本有一个回调函数(它也没有工作),并且读取它是可选的,所以删除它。 – Pebble

+0

但是你想在这里完成什么 - 你想在一个div中显示响应,例如? –

+0

是的,目的是在表单打开的随机网址上显示AJAX结果。 – Pebble