简体   繁体   English

从PHP脚本使用jQuery ajax post方法获取意外结果

[英]Getting unexpected result with jquery ajax post method from php script

This is my form from which i am expecting post results in my div id="response" 我希望这是我的表格,我希望它在div id =“ response”中发布结果

<!DOCTYPE html>
<html>
<head>
<title>AJAX POST</title>
<script src="jquery.js"></script>
<script>
    $(document).ready(function(){
        $('input[name="submit"]').click(function(){
            var username=$('input[name="username"]').attr("value");
            var password=$('input[name="password"]').attr("value");
            var data1=encodeURIComponent(username);
            var data2=encodeURIComponent(password);
            $.post("response.php",{username:data1,password:data2},function(data){
            $("#form").hide();
            $("#response").text(data);
            });
        });
    });
</script>
</head>
<body>
<div id="form">
<form action="response.php" method="post">
<input type="text" name="username" value=""/><br/>
<input type="password" name="password" value=""/><br/>
<input type="button" name="submit" value="submit"/>
</form>
</div>
<div id="response"></div>
</form>
</body>
</html>

This is my server side script 这是我的服务器端脚本

<?php
echo $_POST["username"]."<br/>";
echo $_POST["password"];
?>

After filling the form and clicking the submit button the response that i get is "<br/>" I don't understand this.Please explain. 填写表格并单击提交按钮后,我得到的答复是"<br/>"我不明白。请解释。

To get the input value you need to use .val() not .attr('value') . 要获取输入值,您需要使用.val()而不是.attr('value') .attr('value') will return the value of the attribute which is '' (empty string) here .attr('value')将在此处返回'' (空字符串)的属性值

var username=$('input[name="username"]').val();
var password=$('input[name="password"]').val();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM