2016-10-11 75 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) {})