繁体   English   中英

用jQuery发布PHP的响应?

[英]post response from PHP with jQuery?

我如何将一些文本发布到php doc,然后php doc检查它并返回响应?

在此示例中,检查输入的值是否为“ test”,然后返回并警告TRUE,否则返回并警告FALSE。

HTML / javascript (test_php_response.html)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>test_response</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">

function post_to_php() {

$.post( "test_response.php", function( data ) {
  if (data == true){
      alert("true");
  }else{
     alert("false");
  }
});

}

</script>
</head>


<body>
<a href="javascript:post_to_php();" class='button'>click_here</a>
<form name="response_form"  id="response_form" action="test_response.php" method="POST">
        <input id="response_form_textbox" name="response_form_textbox" type="text"  >
    </form>
</body>
</html>

PHP (test_response.php)

<?php
$text_field = $_POST['response_form_textbox'];
if ($text_field == 'test'){
    echo 'true';
}else{
    echo 'false';
}
?>

演示

----编辑已解决/以下工作版本:-----

HTML / JavaScript

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>test_response</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">

function post_to_php() {

$.post( "test_response.php", $('#response_form').serialize(), function(data) {
  if (data === "true"){
      alert("true");
  }else{
     alert("false");
  }
});

}

</script>
</head>


<body>
<a href="javascript:post_to_php();" class='button'>click_here</a>
<form name="response_form"  id="response_form" action="test_response.php" method="POST">
        <input id="response_form_textbox" name="response_form_textbox" type="text"  >
    </form>
    v.05
</body>
</html>

的PHP

   <?php
    $text_field = $_POST['response_form_textbox'];
    if ($text_field == 'test'){
        echo 'true';
    }else{
        echo 'false';
    }
    ?>

您没有发送任何数据。 $.post的第二个参数用于该数据,但您省略了它。

因此,在您的PHP中, $_POST将为空。

发送表单数据的最简单方法是使用serialize()

$.post( "test_response.php", $('#response_form').serialize(), function( data ) {
  if (data){
      alert("true");
  }else{
     alert("false");
  }
});

参考:

暂无
暂无

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

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