dongsaohu6429 2017-01-26 20:22
浏览 49
已采纳

带有ajax的Jquery变量

I am working on a project and I am trying to use jquery to send a variable to php. This a file called test2.php that I have been using to test out the code, can anyone tell me what I am doing wrong because it should be printing out the variable when you click on the button but nothing is happening.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    var something="hello";
    $("button").click(function(){
        $.ajax({ url: 'test2.php',type: "GET", data: { q : something }});
    });
});
</script>
</head>
<body>
<button>Get External Content</button>
</body>
</html>
<?php
    if(isset($_GET['q']))
{

$q = $_GET["q"];
echo $q;
}
?>
  • 写回答

1条回答 默认 最新

  • doubian0284 2017-01-26 20:35
    关注

    Your code looks generally correct but you have to remember that an AJAX call sends the data "Asynchronously", which means when you click on the button this data is being sent to a separate instance of "test2.php" for processing. It is not reloading the current page with this new data.

    The "test2.php" code you are viewing in browser is only run on the server side once when you first start up the page, and there is no 'q' in the '$_GET' variable at that time. The AJAX request is sending data to a separate instance of the same "test2.php" file and it is receiving some data back, but it is not using that information to load anything into your browser.

    Depending on what you are trying to achieve there are many different solutions. You could use what you receive from your AJAX request to update information on the page like so:

    $.ajax({
        url: "test2.php",
        type: "GET",
        data: { q: something},
        success: function (response) {
            // do something with 'response' here
        }
    });
    

    Or you could have the button instead be a simple <a> tag that reloads the current page in browser with information stored in '$_GET' like so:

    <a href="test2.php?q=something">Button</a>
    

    Then when your PHP code looks for 'q' it would actually find it in the $_GET variable because you reloaded the page.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料