繁体   English   中英

为什么jquery AJAX调用PhP返回DIV所返回的表单不起作用?

[英]Why doesn't a form returned by a jquery AJAX call to PhP into a DIV not work?

我正在尝试编写一个交互式网页,并在此过程中学习较新的(不到10年的)网络技术。 因此,PhP,jquery和AJAX都属于该类别。 我已经将代码简化为仅提出问题的要点。

我希望我的jQuery调用一个PhP程序,该程序将加载两个单独的DIV。 一个是数据显示区域,另一个用于显示过程链中的下一个表单。 我遇到的麻烦是,即使返回的表单显示正确,它也不起作用。

这是主页(demo.php):

<?php 
echo <<<_END
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">     </script>
<script>
//
$(document).ready(function(){
  $("#btnDemo").click(function() {
     $("#PageForm").load("thetest.php", { paramYN: $("#paramYN").val() })
     $("#PageContent").load("nextpage.php");
  });
});

</script>
</head>
<title>The Title</title>
</head>
<body> 
<div id="PageHdr">
    <H4>Heading</h4>
</div>

<div id="PageForm">
    <form action="" id="Login"> 
        <br/>
    To show this form again enter   Y  otherwise enter   N    : <input type="text"    name="paramYN" id="paramYN" size=1>
    <input type="button" name="btnDemo" id="btnDemo" value="test it" /></form>
</div>

<div id="PageContent">
    <P>Put response here</p>
</div>
</body>
</html>
_END;

?>

这是PhP程序“ thetest.php”,该程序决定返回PageForm DIV的内容:

<?php //thetest.php
paramYN = $_POST["paramYN"];
if ($paramYN == "Y")
{
echo <<<_EOF
<form action="" id="Login"> 
<br/>This is the redisplay. Look for the date to change if it works after you click the      test it  button
<br/>To show this form again enter   Y  otherwise enter   N    : <input type="text" name="ParamYN" id="paramYN" size=1>
<input type="button" name="btnDemo" id="btnDemo" value="test it" /></form>
_EOF;
    $thetime = time();
    echo $thetime;
    exit();
}   
else
{
    echo "<html><head><title>PDO login</title></head><body>";
    echo "<h1>Congrats!</h1>";
    echo "</body></html>";
    exit();
}
?>

我只包含nextpage.php程序,因为程序的完整版本需要更新两个DIV。 就此演示而言,它非常简单:

<?php //.php
echo "<h1>This is the new text for this place</h1>";
?>

那我的问题是什么? 是我加载DIV的方式吗? 还是这是行不通的?

首次加载页面时,您将使用jQuery并将单击事件“绑定”到按钮“ btnDemo”。

然后,用户单击按钮“ btnDemo”并触发加载事件。 但是,通过这样做,您将使用已建立的jQuery事件(使用新按钮“ btnDemo”)覆盖以前加载的按钮。 此“新”按钮没有相同的绑定点击事件。

通过将jQuery添加到加载页面“ thetest.php”,您需要在单击后将点击事件重新应用于新加载的按钮。

echo <<<_EOF
<script>
$(document).ready(function(){
  //this will bind the click event to the newly loaded button
  $("#btnDemo").click(function() {
    $("#PageForm").load("thetest.php", { paramYN: $("#paramYN").val() })
    $("#PageContent").load("nextpage.php");
  });
});
</script>
<form> (the rest of your form here...)
_EOF;

你有:

<?php //thetest.php
paramYN = $_POST["paramYN"];
if ($paramYN == "Y")
{

尝试:

<?php //thetest.php
$paramYN = $_POST["paramYN"];
if ($paramYN == "Y")
{

暂无
暂无

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

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