问题与AJAX加载一个PHP脚本,从onclick调用; [英] Issue with AJAX loading a php script, called from an onclick;

查看:116
本文介绍了问题与AJAX加载一个PHP脚本,从onclick调用;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在HTML,CSS,JavaScript和PHP方面有相当强的背景。不幸的是,当涉及到jQuery和Ajax时,我至少可以说是有资格的。我在工作上做网页设计,但主要与酒吧,夜总会(喜欢表演的人)交易。我最近进入了一项需要上述所有内容的工作,另外还有一个使用PHP的mySQL后端。



我有一个主页面。在这个页面上它包含一个表格。这张表是可滚动的,这意味着页面本身只有大约750px(正常屏幕大小),但是只要需要(表格中的信息),表格就可以滚动。最右边的列包含2个按钮,其中1个用于查看该列的详细信息。这个按钮重定向到另一个页面(输入类型=提交和PHP处理重定向),很容易。然而,另一个按钮(输入类型=按钮)被点击(可以说这与项目A相关联)是假设在处理基于项目A的子项目的同一页面上生成另一个表格。再次,这不是一个问题。简单的提交按钮和PHP检查提交按钮是否被按下。现在的问题是数据库中有太多项目,当用户点击按钮查看子项目时,页面会进行快速刷新,使第一个表格(可能有100个项目长)刷新到顶部。我的主要目标是让jQuery或Ajax调用一个外部PHP脚本,它将回显必要的代码,以便在当前html页面中构建另一个表,而无需刷新顶部表。



这是我已经尝试过的。

 < script> 

函数callAjax(){
var xmlhttp;
if(window.XMLHttpRequest)
{//代码为IE7 +,Firefox,Chrome,Opera,Safari
xmlhttp = new XMLHttpRequest();
}
else
{//代码为IE6,IE5
xmlhttp = new ActiveXObject(Microsoft.XMLHTTP);
}

xmlhttp.open(POST,test.php,true);
xmlhttp.send();

document.getElementById(divClass3)。innerHTML = xmlhttp.responseText;
}


< / script>

另外,我在html页面中的代码如下(请指出我曾经有过 test.php代码在我的html文件中。这个工作正常,暂时我没有改变根据我的结果从我的企图):

 < div id =divClass3> 
<?php if(sizeof($ rows2)> 0)echo'


< table class =tableClass3>

< colgroup>
< col class =fifteenper/>
< col class =fifteenper/>
< col class =fifteenper/>
< col class =fifteenper/>
< col class =fifteenper/>
< col class =fifteenper/>
< col class =tenper/>
< / colgroup>

< tbody>
< tr class =tableRowClass3>

< th class =tableHeadingClass1>
heading1
< / th>

< th class =tableHeadingClass1>
heading2
< / th>

< th class =tableHeadingClass1>
heading3
< / th>

< th class =tableHeadingClass1>
heading4
< / th>

< th class =tableHeadingClass1>
heading5
< / th>

< th class =tableHeadingClass1>
heading6
< / th>

< th class =tableHeadingClass1>
heading7
< / th>
< / tr>
< / tbody>
< / table>


< div class =divClass2>

< table class =tableClass2>

< colgroup>
< col class =fifteenper/>
< col class =fifteenper/>
< col class =fifteenper/>
< col class =fifteenper/>
< col class =fifteenper/>
< col class =fifteenper/>
< col class =tenper/>
< / colgroup>

< tbody class =tableBodyClass2>
'?>

<?php if(sizeof($ rows2)> 0){foreach($ rows2 as $ row2):?>
< tr class =tableRowClass2>

< td class =tableDataClass2>
< form method =post> <?php echo $ row2 ['echo1']; ?> < /形式>
< / td>

< td class =tableDataClass2>
< form method =post> <?php echo $ row2 ['echo2']; ?> < /形式>
< / td>

< td class =tableDataClass2>
< form method =post> <?php echo $ row2 ['echo3']; ?> < /形式>
< / td>

< td class =tableDataClass2>
< form method =post> <?php echo $ row2 ['echo4']; ?> < /形式>
< / td>

< td class =tableDataClass2>
< form method =post> <?php echo htmlentities($ row2 ['echo5'],ENT_QUOTES,'UTF-8'); ?> < /形式>
< / td>

< td class =tableDataClass2>
< form method =post> <?php echo htmlentities($ row2 ['echo6'],ENT_QUOTES,'UTF-8'); ?> < /形式>
< / td>

< td class =tableDataClass2>
< form method =post>
< input name =Viewtype =submitvalue =View/>
< input name =WorkIDtype =hiddenvalue =<?php echo $ row2 ['WorkID'];?> /> < /形式>
< / td>

< / tr>
<?php endforeach;}?>

<?php if(sizeof($ rows2)> 0)echo'
< / tbody>
< / table>
< / div>
'?>
< / div>

最后,这是test.php

<?php 


$ query2 =
SELECT
SOMETHING
FROM
TABLE1
INNER JOIN
TABLE2
ON
CAT1 = CAT2
AND
CAT3 =:CAT4
;

$ query_params2 = array(
':CAT4'=> $ _POST ['BUTTON']
);

尝试
{
$ stmt2 = $ db-> prepare($ query2);
$ stmt2-> execute($ query_params2);

$ b $ catch(PDOException $ ex)
{
die(Failed to run query:。$ ex-> getMessage());
}

$ rows2 = $ stmt2-> fetchAll();

?>

我提前感谢任何帮助。我只是发布这个,以便其他人也可以从中受益。我一直无法坚持几天。我见过类似的问题,但没有匹配,所以我想我会试试看。我非常感谢你!

干杯

解决方案

你的脚本的问题在于你在调用ajax之后立即尝试设置innerhtml。 Ajax请求是异步的(除非你告诉他们不要这样做),所以它们将在自己的时间运行,并且在调用之后放置的任何内容都可以在执行之前或之后执行。但基本上除非你告诉ajax调用是同步的(暂停脚本直到你得到响应), xmlhttp.responseText 并不意味着什么。您在常规JavaScript中处理异步请求的方式是通过 onreadystatechange 指定回调函数。例如

 函数myCallback()
{
...
}
xmlhttp.onreadystatechange = myCallBack函数;
xmlhttp.send();

您也可以使用 xmlhttp.onreadystatechange = function(){ ...};



无论采用哪种方式,对于异步调用,都需要该回调。更具体地说,当readystate特别是 200 (成功返回)时,您需要处理回调,例如

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

另一个选项是让它同步,它会冻结你的javascript直到它被加载(这个方法一般不建议)。您可以通过简单地将您的 .open 语句更改为

  xmlhttp 。开( POST, test.php的,假); 

(最后一个参数确定调用是否是异步的(true = async; false = sync)

jQuery



这就是你如何使用普通的javascript做的,但是既然你提到了它,我会强烈建议使用jQuery,因为它可以让你的生活更轻松。下面是使用jQuery的完整ajaxcall函数:

  function ajaxcall() 
{
$ .post('test.php',function(response){
$('#divClass3')。html(response);
});

$ / code>

让我知道您是否对此有何疑问:)


I have a fairly strong background in HTML, CSS, JavaScript and PHP. Unfortunately when it comes to jQuery and Ajax, I am a bit under qualified to say the least. I do web design at work, but deal mainly with bars, nightclubs (people who favour fancy over performance). I have recently came into a job that requires all of the above, plus it has a mySQL backend which uses PHP.

I have a main page. On this page it contains a table. This table is scrollable meaning that the page itself is only about 750px (normal screen size), but the table can scroll for as long as it needs to (information pulled from the DB). The right most column contains 2 buttons, 1 which is to view the details of that column. This button redirects to another page (input type=submit and PHP handles the redirection), easy. The other button however (input type=button) when clicked (lets say this is associated with item A) is suppose to generate another table on the same page which deals with sub items based on item A. Again at first this wasn't an issue. Simple submit button and PHP checks if that submit button was pressed. Now the issue is that there are so many items in the DB that when the user clicks on the button to view the sub items, the page does a quick refresh which makes the first table (possibly 100's of items long) refresh to the top. My main goal is to just have jQuery or Ajax call an external PHP script that will echo the necessary code in order to "build" the other table in the current html page, without refreshing the top table.

Here is what I have / have tried.

<script>

function callAjax() {
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","test.php",true);
xmlhttp.send();

document.getElementById("divClass3").innerHTML=xmlhttp.responseText;
}


</script>

Also, my code in the html page is as follows (Please advise that I used to have the "test.php" code inside my html file. This worked correctly and for the time being I haven't changed based on my results from my attempts) :

<div id="divClass3">
<?php if (sizeof($rows2) > 0) echo'


    <table class="tableClass3">

        <colgroup>
            <col class="fifteenper" />
            <col class="fifteenper" />
            <col class="fifteenper" />
            <col class="fifteenper" />
            <col class="fifteenper" />
            <col class="fifteenper" />
            <col class="tenper" />            
        </colgroup>

        <tbody>
            <tr class="tableRowClass3">

                <th class="tableHeadingClass1">
                    heading1
                </th>

                <th class="tableHeadingClass1">
                    heading2
                </th>

                <th class="tableHeadingClass1">
                    heading3
                </th>

                <th class="tableHeadingClass1">
                    heading4
                </th>

                <th class="tableHeadingClass1">
                    heading5
                </th>

                <th class="tableHeadingClass1">
                    heading6
                </th>

                <th class="tableHeadingClass1">
                    heading7
                </th>    
            </tr>
        </tbody>
    </table>


<div class="divClass2">

    <table class="tableClass2">

        <colgroup>
            <col class="fifteenper" />
            <col class="fifteenper" />
            <col class="fifteenper" />
            <col class="fifteenper" />
            <col class="fifteenper" />
            <col class="fifteenper" />
            <col class="tenper" />         
        </colgroup>

        <tbody class="tableBodyClass2">
    '?> 

    <?php if (sizeof($rows2) > 0) {foreach($rows2 as $row2): ?>
            <tr class="tableRowClass2">

                <td class="tableDataClass2">
                    <form method="post"> <?php echo $row2['echo1']; ?> </form> 
                </td>

                <td class="tableDataClass2">
                    <form method="post"> <?php echo $row2['echo2']; ?>  </form>
                </td>

                <td class="tableDataClass2">
                    <form method="post"> <?php echo $row2['echo3']; ?>  </form> 
                </td>

                <td class="tableDataClass2">
                    <form method="post"> <?php echo $row2['echo4']; ?>  </form> 
                </td>

                <td class="tableDataClass2">
                    <form method="post"> <?php echo htmlentities($row2['echo5'], ENT_QUOTES, 'UTF-8'); ?> </form>
                </td>

                <td class="tableDataClass2">
                    <form method="post"> <?php echo htmlentities($row2['echo6'], ENT_QUOTES, 'UTF-8'); ?> </form>
                </td>

                <td class="tableDataClass2">
                    <form method="post"> 
                    <input name="View" type="submit" value="View" />
                    <input name="WorkID" type="hidden" value="<?php echo $row2['WorkID']; ?>" /> </form>
                </td>

            </tr>
        <?php endforeach;} ?>

    <?php if (sizeof($rows2) > 0) echo'
        </tbody>
        </table>
        </div>   
    '?>
        </div>

And finally this is test.php

<?php


        $query2 = "
        SELECT 
            SOMETHING 
        FROM 
            TABLE1 
        INNER JOIN 
            TABLE2 
        ON 
            CAT1=CAT2
        AND
            CAT3 = :CAT4
        ";

        $query_params2 = array( 
            ':CAT4' => $_POST['BUTTON'] 
        );

        try 
        { 
            $stmt2 = $db->prepare($query2); 
            $stmt2->execute($query_params2);        
        }

        catch(PDOException $ex) 
        { 
            die("Failed to run query: " . $ex->getMessage()); 
        } 

        $rows2 = $stmt2->fetchAll();

?>

I appreciate in advance any help given. I am simply posting this so that others can benefit from it too. I have been stuck for a few days with no avail. I have seen similar issues, but nothing matching this so I thought I would give it a try. I thank you very much!

Cheers

解决方案

First: the problem with your script is that you're trying immediately set the innerhtml after calling ajax. Ajax requests are Asynchronous (unless you tell them not to be), so they will run on their own time, and whatever you put after the call might execute before or after. But basically unless you tell the ajax call to be synchronous (which pauses the script until you get a response), xmlhttp.responseText doesn't mean anything yet. The way you handle an asynchronous request in regular javascript is to specify a callback function through onreadystatechange. E.g.

function myCallback()
{
   ...
}
xmlhttp.onreadystatechange=myCallback;
xmlhttp.send();

you could also do this anonymously with xmlhttp.onreadystatechange = function() { ... };

Either way, for asynchronous calls, you need that callback. And more specifically, you need to handle the callback when the readystate is specifically 200 (successful return), e.g

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

The other option is to make it synchronous, which freezes your javascript until it's loaded (this method is generally not recommended). You could do this by simply changing your .open statement to

xmlhttp.open("POST","test.php",false);

(the last parameter determines whether the call is asynchronous or not (true=async; false=sync)

jQuery

So that's how you would do it in regular javascript, but since you mentioned it, I would highly recommend using jQuery because it will make your life way easier. Here is your entire ajaxcall function using jQuery:

function ajaxcall()
{
    $.post('test.php', function(response) {
        $('#divClass3').html(response);
    });
}

Let me know if you have any questions about how this works :)

这篇关于问题与AJAX加载一个PHP脚本,从onclick调用;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆