从jquery发送值到php无法正常工作

时间:2016-07-25 16:46:43

标签: javascript php jquery html ajax

我正在学习jquery和ajax。我尝试了以下代码,从jquery发布值到php。但它不起作用。有人可以告诉我,我在这里做了什么错,解决方案是什么。

我只希望PHP服务器端代码打印value1,该值由基于Jquery的客户端代码发送。

<html>

<head>
    <title>Practice 1</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>

<?php 
    if (isset($_POST['data'])) { 
        $data = $_POST['data']; 
        print( "data is: $data" ); 
        return; 
    } 
?> 

<body onload='process()'>
    <script type="text/javascript"> 
    $.post(window.location, {'data': "value1"}, function (data) {
        $('#response').text(data);
    }); 
    </script> 
</body>

</html>

1 个答案:

答案 0 :(得分:0)

您正在尝试输出一个不存在的元素&#39; #response&#39;,也缺少过程功能。

尝试这样的事情:

<html>
<head>
    <title>Practice 1</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> 
    </script>
</head>

<?php 
    if (isset($_POST['data'])) { 
        $data = $_POST['data']; 
        print( "data is: $data" ); 
        return; 
    } 
?> 

<body>
<div id="response"></div>
    <script type="text/javascript"> 
        $.post(window.location, {'data': "value1"}, function (data) {
            $('#response').text(data);
        }); 
    </script> 
</body>
</html>