【问题标题】:calling php page in a div onclick a button using ajax calls在 div 中调用 php 页面 onclick 使用 ajax 调用的按钮
【发布时间】:2014-12-17 06:32:55
【问题描述】:

我正在使用 ajax 脚本通过单击按钮调用 php 页面 "MAINPAGE.PHP",该页面包含一个 echo 语句到一个 id 为 "YOURDIV" 但它不调用 "MAINPAGE.PHP" 的 div 中,请参阅下面的代码和直接在你的 localhost 上运行它:

新更新:

<!DOCTYPE html>
<html>
<head>

<script>







function yourFunction($x)//passed $url as $x as you said 
{

var xmlhttp = new XMLHttpRequest();
var url = "mainpage.php";// url to where to send
var params = "url=<?php echo $x;?>"; // here we add the php var $url as an 'url' request         parameter
xmlhttp.open("POST", url, true);

//Send the proper header information along with the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);// add the length into header
xmlhttp.setRequestHeader("Connection", "close");

xmlhttp.onreadystatechange = function() {//Call a function when the state changes.
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText); // or do some other stuff
}
}
xmlhttp.send(params);// requesting with parameters. params contains value of url 

var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.open("POST","mainpage.php",true);
xmlhttp.send();

xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{

 $('.container').html(xmlhttp.responseText);
}
}


}
</script>
</head>

<body>
<!--this is the main form,if we press submit button four divs are formed , basically designing         part-->
<form method="POST" action="#">
<input type="text" name="search"><input type="submit" name="submit">
</form>

<?php
if(isset($_POST['submit']))
{ 
$button = $_POST ['submit'];
$search = $_POST ['search'];
$con=mysql_connect("localhost","root","");//connecting from database
if(!$con)
{
die("error:".mysql_error());
}
mysql_select_db("database",$con);
$query="SELECT * FROM tablename ";
$result=mysql_query($query);//tablename contains two fields of four records: 1-S.no, 2- URL like     www.google.com, yahoo, bing,rediff

while($runrows = mysql_fetch_assoc($results))// runrows is array with all the table content
{
$url = $runrows ['URL']; //$url now contains url from the database
echo"<div class='main' style='position:relative;border:1px solid #A5BEBE;background-        color:#E7EFEF;width:84%;  '> 
<b> sometext:-</b><a href='#'>$url</a><br>
</p>
<!-- passed $url in yourfunction as you said-->
<input type='submit' value='expand' class='myButton'  name='button1'     onclick='yourFunction($url);'            style='position:absolute;left:85%;top:4%;background:#B20000;color:white;width:70px;height:20px;font-            size:15px;' >";
echo "<div  class='container' id='yourdiv' style='background:white; '></p>";
echo "</div>";
echo "</div>";
}
mysql_close($con);
}
?>
</body>
</html>

这是我在 mainpage.php 中使用 $url 的方式

<?php
echo 'the response is ', $_POST['url'];//here i want the value of $url for further working
$z=array("google","yahoo","bing","rediff");
for($i=0;$i<=3;$i++){
if (ereg(".*($z[$i]).*", $url))
{
switch($i)
{
case 0:
$a=fopen($url,"r");//opening google site
echo "you have entered"$a;//you have entered www.google.com
break;

case 1:
$a=fopen($url,"r");
echo "you have entered"$a;
break;

case 2:
$a=fopen($url,"r");
echo "you have entered"$a;
break;

case 3:
$a=fopen($url,"r");
echo "you have entered"$a;
break;    
}
}
}
?>

当您运行上面的代码时,您会看到四个带有四个按钮的 div,因此,每当我按下四个按钮中的任何一个时,mainpage.php 都必须将消息回显到所需的 div 中,但不是。请建议任何人我应该怎么做。

提前谢谢。 @igor,如果您不了解任何内容,我会向您解释。我发送给您只是为了理解这个冗长但易于理解的概念。

更新1:

1.- 我已经粗略地尝试了这段代码来传递 $url 及其工作::

<script>
function sendValue(id){
window.location='edit.php?ID=' + id;
}
</script>
<?php $url="hello";?>
<form method="POST" action="#">    
<input type="button" onclick="javascript:sendValue('<?php echo $url; ?>')>
</form>

但我的整个代码都在 php 中,所以我尝试了这个不起作用::

<script>
function sendValue(id){
window.location='mainpage.php?ID=' + id;
}
</script>
<?php
$url="jhdbvkjsbd";
echo '<form method="POST" action="#">
<input type="button" onclick="javascript:sendValue($url);">
</form>';
?>

所以请解释如何以正确的方式传递 $url,但应该在 php 中。

2.- 其次在 mainpage.php 中的 switch case 、ereg 函数和 $a=fopen($url,"r");当我直接在while循环中加载这个mainpage.php时运行良好,方法是将它包含在php中,而不是在点击按钮后加载它,请参阅下面的代码:

while($runrows = mysql_fetch_assoc($results))// runrows is array with all the table content
{
$url = $runrows ['URL']; //$url now contains url from the database
echo"<div class='main' style='position:relative;border:1px solid #A5BEBE;background-        color:#E7EFEF;width:84%;  '> 
<b> sometext:-</b><a href='#'>$url</a><br>
</p>
<!-- passed $url in yourfunction as you said-->
<input type='submit' value='expand' class='myButton'  name='button1'     onclick='yourFunction($url);'            style='position:absolute;left:85%;top:4%;background:#B20000;color:white;width:70px;height:20px;font-            size:15px;' >";
echo "<div  class='container' id='yourdiv' style='background:white; '></p>";

include('mainpage.php'); //this statement directly loads mainpage.php and shows data in this div but i want the data to be shown after clicking the button

echo "</div>";
echo "</div>";
}
mysql_close($con);
}

如果您可以在 mainpage.php 中访问此 $url 变量,那么希望它可以工作。

最新更新:

function showRSS(str) 
{

$('#loading').html('<img src="Preloader_1.gif"> loading...');


var xmlhttp = new XMLHttpRequest();
var url = "mainpage.php?q=+str";// url to where to send
var params = "url="; // here we add the php var $url as an 'url' request parameter
xmlhttp.open("POST", url, true);

//Send the proper header information along with the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);// add the length into header
xmlhttp.setRequestHeader("Connection", "close");

xmlhttp.onreadystatechange = function() {
  if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    alert(xmlhttp.responseText); 
  }
}
xmlhttp.send(params);

var xmlhttp;
if (window.XMLHttpRequest)
  {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  }
else
  {
    // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

  xmlhttp.open("POST","mainpage.php?q="+str,true);
  xmlhttp.send();

  xmlhttp.onreadystatechange=function()
{
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
  {
     $('.container').html(xmlhttp.responseText);
  }
}

}

我想用 class="main" 显示在主 div 中加载图像,直到内容加载到容器 div 中,并且一旦加载该图像应该自动淡出,请告诉我我在哪里做错了

echo"<div class='main' style='position:relative;border:1px solid #A5BEBE;background-color:#E7EFEF;width:84%;'><div id='loading'>

</div> 
<b> sometext:-</b><a href='#'>$url</a><br>
</p>
<!-- passed $url in yourfunction as you said-->
<input type='submit' value='expand' class='myButton' name='button1' onclick='yourFunction($url);'style='position:absolute;left:85%;top:4%;background:#B20000;color:white;width:70px;height:20px;font-            size:15px;' >";
echo "<div  class='container' id='yourdiv' style='background:white; '></p>";
echo "</div>";
echo "</div>";


<style>
#loading {
width: 100%;
height: 100%;
top: 0px;
left: 0px;
position: fixed;
display: block;
opacity: 0.8;
background-color: #000;
z-index: 99;
text-align: center;
}
#loading-image {
position: absolute;
top: 40%;
left: 45%;
z-index: 100;
}
</style>

【问题讨论】:

  • id 始终是唯一的,而在 for loop 中它实际上并不像。
  • 是的,我忘记了,那我应该使用 class 而不是 id ,是否可以,即 document.getElementByclass("container").innerHTML=xmlhttp.responseText;
  • 如果你打算使用 jQuery,请坚持使用 jQuery。 JQuery 支持 Ajax,它为您处理所有跨浏览器的东西。 api.jquery.com/jquery.ajax
  • jquery 仅用于设计问题,但对于按钮,我使用 ajax 调用。请解释我是否使用 class 而不是 id 可以吗?
  • 你不应该有重复的 ID,所以从这个意义上说,是的。

标签: javascript php ajax


【解决方案1】:

是否可能,即 document.getElementByclass("container").innerHTML=xmlhttp.responseText

是的,去做吧:

$('.container').html(xmlhttp.responseText);

顺便说一下您不检查xmlhttp 状态码,仅当状态码=200 和readyState=4 时才会从服务器返回响应。但是你马上检查。

来自here

xmlhttp.onreadystatechange=function()
{
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
  {
      document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
  }
}

更新

在 for 循环中,我使用了一个包含 url 的 $url 变量,并且这个相同的 $url 也存在于 mainpage.php 中。所以通过这个 $url 他们是在 maipage.php 中执行的一些更进一步的 echo 语句。你能告诉我为什么这个 $url 在 mainpage.php 中不起作用

在您的原始 php 文件中,您希望管理某些 $url 将其传递到 mainpage.php。你可以把它作为ajax请求的数据来做。

<?php $url='smth'; ?>

var xmlhttp = new XMLHttpRequest();
var url = "mainpage.php";// url to where to send
var params = "url=<?php echo $url;?>"; // here we add the php var $url as an 'url' request parameter
xmlhttp.open("POST", url, true);

//Send the proper header information along with the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);// add the length into header
xmlhttp.setRequestHeader("Connection", "close");

xmlhttp.onreadystatechange = function() {//Call a function when the state changes.
  if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    alert(xmlhttp.responseText); // or do some other stuff
  }
}
xmlhttp.send(params);// requesting with parameters.

ma​​inpage.php 中,您将传递的 POST 参数 'url' 寻址为:

$_POST['url']  

更新 2

for 循环中,您已经定义了目标 div:

 echo "<div  class='container' id='yourdiv' style='display:none;background:white; '>";
  • 去掉不唯一if div:id='yourdiv{$i}'
  • 删除style='display:none;,而不是将div留空,它会缩小成点。

现在您将它们称为#yourdiv1#yourdiv2 等。

echo "<div class='container' id='yourdiv{$i}'></div>";

更新 3

我为你写了一个test case 但是将回复插入到相应的div 会花费你更多的精力......

更新 4

  1. input 上单击yourFunction() 有效,但没有传入url 参数。
  2. 带有 xhr 的代码(我已经给你了)在页面加载/就绪时工作;它应该在函数中调用,并且 $url 从按钮正确传递给它。为按钮分配唯一的 id 并将它们传递给 yourFunction(),然后将它们传递给 xhr。
  3. ereg(".*($z[$i]).*", $url) 已过时,最好使用preg_match(),但不是必需的。
  4. 变量$url 没有在mainpage.php 中定义(例如$a=fopen($url,"r");),而是使用$_POST['url']:$a=fopen($_POST['url'],"r");
  5. 什么是$b
  6. 请以适当的缩进显示您的代码,这表明您的编码态度并影响读者。
  7. 您可以从您的问题中删除旧代码,只留下您目前拥有的代码,并在注释中写下哪些有效,哪些无效。

更新 5

  • 您正确地将 $url 传递给 yourFunction() 然后通过 xhr 传递给 mainpage.php。
  • 但在 mainpage.php 中,您回显两次:echo 'the response is ', $_POST['url'] 并在其中一种切换情​​况下:echo "you have entered"$a;
  • 如果您有 mainpage.php 回显'the response is ', $_POST['url'],那么它会在 xhr 上正确返回。但是,当您使用 ereg() 添加 switch case 并且现在没有响应时 - 这段代码中的某处出现了错误。
  • $a=fopen($url,"r"); 不是通过 url 获取内容的最佳解决方案(您要关闭它吗?)。为此,您宁愿使用 cUrl 库或 file_get_contents()

更新 6

这不起作用:

$url="jhdbvkjsbd";
echo '<form method="POST" action="#">
<input type="button" onclick="javascript:sendValue($url);">
</form>';

因为在 echo 中您使用 ' 而不是 " 并且在 ' 中未计算变量。在 echo 中试试这个:

echo '<form method="POST" action="#">
<input type="button" onclick="javascript:sendValue('.$url.' );">
</form>';

include('mainpage.php'); //此语句直接加载mainpage.php并在此div中显示数据但我希望在单击按钮后显示数据

如果你想这样做,那么你可以先隐藏 mainpage.php 中的日期,方法是用带有一些类和 id 的 div 包装它们:

.some-class{ 显示:无; }

然后单击按钮,从选定的 id 中删除该类,数据将可见。

更新 7

我们可以在其中添加加载图像直到内容加载吗?

由于 xhr 是一个异步进程,您无法知道它何时开始和结束。函数onreadystatechange 检查要发生的事件。函数open 打开进程。所以你只需用它们包装逻辑:

// here the ajax call is initiated, made open
xmlhttp.open("POST", url, true);
// so down here you might insert JS code to put image on screen
...
// this function checks if response is ready "readyState == 4" so inside you might set a code to remove image
xmlhttp.onreadystatechange = function() { 
   if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
     <remove image code...>
     alert(xmlhttp.responseText); // or do some other stuff
   }
}

【讨论】:

  • 干得好,先生。 Igor Savinkin ,但他们的另一个问题是,在 for 循环中我使用了一个包含 url 的 $url 变量,并且这个相同的 $url 也存在于 mainpage.php 中。所以通过这个 $url 他们是在 maipage.php 中执行的一些更进一步的 echo 语句。你能告诉我为什么这个 $url 不能在 mainpage.php 中工作吗?如果你解决了这个问题会很有帮助的
  • 好的,我已经在我之前的脚本中添加了你的脚本,上面的函数 ""function yourFunction()"" 并在 mainpage.php 中添加了 ""$_POST['url']""这个 style=display none 用于默认隐藏 div 容器,如果我删除它,则 div 已经显示,没有这个 icant 默认隐藏它们
  • @Darkknight,现在你在 mainpage.php 中返回 $_POST['url'] 作为响应文本: 并通过调试工具 (F12) 查看响应。
  • 嘿,我遇到了问题,它显示“smth”,这是 但我已经在 for 循环中有它的值。实际上,我在编码中展示了这一点,但是我从数据库连接中获取了 $url 的所有值,并通过从按钮调用它来使用 mainpage.php 中的 url,因此这个 $url 使用 for 循环从数据库中获取值,我希望它们在 mainpage.php 中传递以进行进一步操作....现在您可能得到正确的概念
  • 我知道这并不容易,但它对我的项目非常重要,你的努力不会白费。如果我删除了你的 "" 我只得到这个“响应是”而不是“响应是 smth”所以代替这个 smth 我如何从我的数据库中获取 url 文本
【解决方案2】:

我不确定我是否完全理解了您的问题,但这里有一些清理工作。注:未经测试。几个额外的问题:为什么你对buttons.parent() 的显示和隐藏有不同的处理方式,你能详细说明你想要什么吗?

$(function(){
  var $btns = $('.myButton'),
      $moms = $btns.parent();

  $('body').on('click', '.myButton', function(e) {
    var $ct = $(this).next("div.container"),
        isCollapsed = this.value == 'expand';
        this.value = isCollapsed ? 'expand' : 'collapse';
        $ct[isCollapsed ? 'show':'hide']('slow');

        // sorry got lazy here
        // also, why are you treating the conditions differently, not oppositely?
        if (isCollapsed)
          $moms.show('slow');
        else
          $btns.not($(this)).parent().hide('slow');

        // if this is the button you want to send ajax call
        $.post('mainpage.php', function(data) {
          $('.container').html(data);
        });
  });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 2012-04-27
    相关资源
    最近更新 更多