2016-10-11 74 views
-1

我的POST方法不会显示在网页上,但我的GET方法即使在我的global.js中没有创建方法。 GET方法是否附带POST?我希望我的POST不显示为GET。我怎么做?我知道我的POST工作我认为,因为在网络(即在与控制台的浏览器),POST方法在那里,预览打印出$_POST$_SESSION。如何让POST显示在页面上而不是GETPOST方法不显示,但GET方法确实

Button.php

<!doctype html> 
<html> 
    <head> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">    </script> 
    <script src ="global.js"></script> 
    <title>Button POST</title> 
    </head> 
    <body> 
     <button id ="postbutton" onclick="location.href='storage.php'">GO</button><br> 
    </body> 
</html> 

storage.php

<?php 
print_r($_POST); 
if(isset($_POST['json'])){ 
    $_SESSION['object'] = $_POST["json"]; 
    print_r($_SESSION); 
    echo 'True'; 
}else { 
    echo 'False'; 
} 

global.js

var oject = [{name:'John', age:17},{name:'James', age:22}]; 
var json = JSON.stringify(oject); 


$(document).ready(function(){ 
    $('#postbutton').click(function(){ 
    $('#output').html('sending..'); 
     var jobject = JSON.stringify(oject); 
     console.log(jobject); 
     $.ajax({ 
     method:'post', 
     url:'storage.php', 
     data:{json:oject}, 
     }) 
     .done(function(data){ 
     console.log(data); 
    }); 
    }); 
}); 
+1

好吧,您正在设置window.location ....您无法进行Ajax调用并同时设置位置。你为什么重定向? – epascarello

+0

@epascarello这只是一个例子,我正在做的是将其重定向到其他不是'storage.php'的页面。认为这没有什么区别,但似乎是这样。 – CBegin

+0

那么你需要在Ajax调用完成后重定向。所以把它放在完成的方法中。 – epascarello

回答

1

您的GET方法是有效的,因为您使用了与location.href方法的onclick.That将始终使用GET方法重定向,因此它可以显示您的输出!但要使用POST method in ajax,您需要删除onclick方法并将返回数据附加到body元素。

Button.php

<!doctype html> 
    <html> 
    <head> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">    </script> 
    <script src ="global.js"></script> 
    <title>Button POST</title> 
    </head> 
    <body> 
     <button id ="postbutton">GO</button><br> 
    </body> 
</html> 

global.js

var oject = [{name:'John', age:17},{name:'James', age:22}]; 
var json = JSON.stringify(oject); 


$(document).ready(function(){ 
    $('#postbutton').click(function(){ 
    $('#output').html('sending..'); 
     var jobject = JSON.stringify(oject); 
     console.log(jobject); 
     $.ajax({ 
     method:'post', 
     url:'storage.php', 
     data:{json:oject}, 
     }) 
     .done(function(data){ 
     $("body").append(data); 
    }); 
    }); 
}); 
+0

感谢您的答案:D它现在看起来像是有效,但是如何将其重定向到其他页面并仍然具有该值?我正在做的是将该值存储到'storage.php'中,并将该值用于另一个页面。 – CBegin

0

为什么有按钮,你碰巧你在同一时间拨打$.ajax()一个onclick

<button id ="postbutton" onclick="location.href='storage.php'">GO</button><br>

如果您想使用$.ajax()不需要onclick。如果符合条件并且想要将用户重定向到其他位置,则可以拨打location.href内部done(function(data) {})