【问题标题】:AJAX: How to change a value on client side as well as server side on button click?AJAX:如何在单击按钮时更改客户端和服务器端的值?
【发布时间】:2014-11-16 19:55:12
【问题描述】:

在接下来的SSCCE中,

  1. 我有一个字符串,其中包含三个divs 的 HTML。
  2. 我将style="display:none;" 属性添加到除第一个之外的所有divs。
  3. 我在除最后一个之外的所有divs 中添加了一个按钮,并添加了一个JS onclick 事件监听器,这应该将当前div 的样式属性更改为style="display:none;"(当前div的id 属性传递给JS 函数。)和下一个div 的(它的id 也传递给JS 函数)样式属性到style="display:block;"
  4. 我将submit 按钮添加到提交form 的最后一个div。我没有编写form 的action 属性或此按钮的任何事件侦听器,因为这不是现在的问题。
  5. 我打印 div。

问题:

传递给按钮单击事件的 JS 事件侦听器的 currentId 和 nextId 在名为 returnCurrentId 的函数中计算,该函数将 $array_of_divs 和 $array_of_ids 作为参数。然后它检查哪个div 有style="display:none;" 并将其设置为current_id。那么$array_of_ids中它旁边的id就变成了next_id。

当 JS 更改 divs 的样式属性时,就会出现问题,而 ids 已在客户端传递给它,而在服务器端没有任何变化。所以在服务器端,相同的$array_of_ids 被传递给returnCurrentId,而显示属性没有任何变化,因此返回第一个和第二个div 的相同ids。它们被传递给 JS,然后再次显示相同的 div。

我的努力:

所以我一直在这里阅读 AJAX,我尝试在 XMLHTTPRequest.open(GET, URL, TRUE) 的 URL 中发送一个名为 pass_back 的变量,并在服务器端尝试检查 $_REQUEST 是否包含它,并且当它发生时,我对样式属性进行相同的更改,但它似乎不包含它。

问题:

我预计我将代码块放在了错误的位置,但是我应该把它放在哪里。

那么谁能给我一些提示/建议/解决方案?

<?php
echo '<html><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
    <script>
        function clickButton(currentId, nextId) {
            alert(currentId+","+nextId); //check
            
            document.getElementById(currentId).style.display = "none";
            document.getElementById(nextId).style.display = "block";
            document.getElementById(nextId).style.border = "5px solid red";//check
            
            //**************************
            var xmlhttp;
            if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); }
            else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }

            xmlhttp.open("GET","C:/xampp/htdocs/testing.php?pass_back="+"pass_back",true);
            xmlhttp.send();
            //**************************
    
        }
    </script>
</head><body>';


//String of all the div's
$haystack = '<div id="div1" style="width:500px; height:250px; background-color:#fd77ba">Div1</div>
<div id="div2" style="width:500px; height:250px; background-color:#7781fd">Div2</div>
<div id="div3" style="width:500px; height:250px; background-color:#77fd9b">Div3</div>';

//Adding divs as DOM objects to an array
require 'C:\\xampp\\htdocs\\simple_html_dom.php';
$html = str_get_html($haystack);
foreach ($html->find('div') as $div) {
    $array_of_divs[] = $div;
}

//Extract id attributes from all elements of $array_of_divs and add to $array_of_ids
foreach ($array_of_divs as $div) {
    $array_of_ids[] = $div->id;
}

//Add style="display:none;" property to all divs except the first one
for ($i=1; $i<count($array_of_divs); $i++) {
    $array_of_divs[$i]->style = 'display:none;';
}

//Strings of the pseudo button to navigate to the next div on the same page and real button to navigate to another page
$pseudo_btn = '<button type="button" onClick="clickButton(\''.returnCurrentId($array_of_divs, $array_of_ids)['current_id'].'\',\''.returnCurrentId($array_of_divs, $array_of_ids)['next_id'].'\')" style="font-family:Oxygen,sans-serif; font-style: normal;font-variant: normal;font-weight: normal;font-size: 99%;line-height: normal;font-size-adjust: none;font-stretch: normal; background-color: #494f50; color: #ffffff; padding-top: 5px;padding-right: 10px;padding-bottom: 5px; padding-left: 10px;margin-top: 50px;margin-right: 10px;margin-bottom: 50px;margin-left: 10px; text-decoration:none;">Submit</button>';
$real_btn = '<span style="background-color:red;"><input type="submit" name="submit" value="Submit" style="font-family:Oxygen,sans-serif; font-style: normal;font-variant: normal;font-weight: normal;font-size: 99%;line-height: normal;font-size-adjust: none;font-stretch: normal; background-color: #494f50; color: #ffffff; padding-top: 5px;padding-right: 10px;padding-bottom: 5px; padding-left: 10px;margin-top: 50px;margin-right: 10px;margin-bottom: 50px;margin-left: 10px; text-decoration:none;"></span>';

//Add $pseudo-btn to all except last div on this page, add $real_btn to the last div
$last_id = end($array_of_ids);
for ($j=0; $j<count($array_of_ids); $j++) {
    if ($array_of_ids[$j] !== $last_id ) {
        $array_of_divs[$j]->innertext .= $pseudo_btn;
    } else {
        $array_of_divs[$j]->innertext .= $real_btn;
    }
}

//Print all the divs
echo '<form method="post" enctype="multipart/form-data" accept-charset="utf-8">';
foreach ($array_of_divs as $div) { echo $div; }
echo '</form>';

//**********************************************
//IF $_REQUEST CONTAINS pass_back (i.e. THE BUTTON HAS BEEN PRESSED, CHANGE DISPLAY PREPERTY OF CURRENT AND NEXT DIV
if (array_key_exists('pass_back',$_REQUEST)) {
        foreach ($array_of_divs as $divs_el) {
            if ( $divs_el->id == returnCurrentId($array_of_divs, $array_of_ids)[current_id] ) {
                $divs_el->style = 'display:none;';
            } else if ( $divs_el->id == returnCurrentId($array_of_divs, $array_of_ids)[next_id] ) {
                $divs_el->style = 'display:block;'; 
            }
        }
} else {
    echo '$_REQUEST does not contain pass_back';
}
//***********************************************

//This function returns the id of the current div which is displayed.
function returnCurrentId($array_of_divs, $array_of_ids) {
    for ($c=0; $c<count($array_of_divs); $c++) {
        $style_value = $array_of_divs[$c]->style;
        $style_value = preg_replace('/\s+/', '', $style_value);//This removes all kinds of white space.
        if (strpos($style_value,'display:none') === false) {
            $current_id= $array_of_divs[$c]->id;
            break;
        }
    }
    $current_position = array_search($current_id, $array_of_ids);
    $next_id = $array_of_ids[$current_position + 1];
    $array_to_pass= array('current_id'=>$current_id, 'next_id'=>$next_id);
    return $array_to_pass;
}



echo '</body></html>';
?>

【问题讨论】:

  • 这对你的项目来说是一种糟糕的方式。您可以使用 PHP 来构建您的原始 HTML 页面,但除非您从数据库中获取信息,或者您有大量重复代码,否则只需将 HTML 和 JavaScript 分开。你的 JavaScript 应该真的在一个外部页面上,所以它被缓存到浏览器内存中。如果您必须在自己的页面上遍历 DOM,而不是使用 PHP,请使用 JavaScript。您可以简单地拥有一个使用 CSS 影响的 HTML 类属性,而不是使用 PHP 创建的 HTML 进行样式设置。如果您需要在事件发生时设置样式,则使用 JavaScript。
  • 供您使用 AJAX 用于将数据发送到通常不同的 PHP 页面。您使用$_GET['property'] 获取$_GET url 的value 部分,它显示为:?property=value&amp;prop=val。换句话说,在 PHP 页面上的? 之后,您使用xhr.open('GET', 'here.php?property=value&amp;prop=val') 分配。您通常不会在 xhr.status === 200 &amp;&amp; readyState === 4 上将 HTML 发送回您的 JavaScript onreadystatechang。当使用您的 PHP 页面进行响应时,您通常将信息存储在一个 PHP 关联数组中,您可以在echo json_encode($arrayHere);.
  • @zarah 我认为您应该在此位中放置一个有效的 HTTP URL: xmlhttp.open("GET","C:/xampp/htdocs/testing.php?pass_back="+"pass_back" ,真的);尝试使用类似localhost/testing.php?pass_back=passback c:/ 的协议不是有效的协议
  • @Zarah,看起来你可以添加&lt;link rel='stylesheet' type='text/css' href='yourCSS.css' /&gt;,你可以将你的CSS页面放在一个文件夹中,对吧?那你应该。您可以将 AJAX 发送到同一页面,但随后您必须向您的页面添加一堆 PHP 代码以确保初始状态和 AJAX 状态不同。换句话说,添加一堆 PHP 条件,这样您就不会收到包含您已经用于制作页面的 HTML 代码的 JSON 响应。最后,C:/xampp/htdocs/testing.php 应该是localhost/testing.php。
  • 了解以下内容很重要:当您将 URL 放入浏览器地址栏中时,您的服务器会查看它是否为 PHP。如果是,它会在将代码吐出给客户端之前运行代码的 PHP 部分。其中一些代码可能会呈现 HTML。一旦客户端通过浏览器获取代码,HTML 就会运行。如果 HTML 中有 &lt;script&gt; 标记,JavaScript 会运行它可以运行的任何东西。由于您并不总是知道客户端接下来会做什么,因此您可以创建将在事件发生时执行的事件。

标签: javascript php html ajax xmlhttprequest


【解决方案1】:

Zara,一些可能对你有帮助的想法:

正如我在评论中所说,尝试改变这一点:

xmlhttp.open("GET","C:/xampp/htdocs/testing.php?pass_back="+"pass_back",true);

例如:

xmlhttp.open("GET","testing.php?pass_back="+"pass_back",true);

考虑到这是通往 Web 服务器中名为 testing.php 的文件的有效路径。 open() 方法的 url 参数必须是 服务器 上文件的地址,并且您必须使用指向该文件的有效 URL。

另一个想法。您可以使用这种方法发送帖子信息:

xmlhttp.open("POST","testing.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("passback=passback");

所以你可以尝试使用 POST 而不是 GET 来发送它,看看会发生什么。它可能会为这件事带来一些启示。

更多的东西。

可能由于您的 php 配置,$_REQUEST 不包含任何内容,而 $_GET 包含。这可能是检查 $_GET 而不是 $_REQUEST 的好理由。但是,如果您确实想使用 $_REQUEST,here 您可以找到有关该主题的更多信息。

编辑

以下代码(基于您的)适用于我(debian APACHE/php 5.4)。我已将所有代码放在同一页面上。我不太喜欢它,但只是指出它有效。 AJAX 部分将数据发送到 main.php,而 main.php 只是将接收到的内容发回。然后 AJAX 部分简单地提醒来自服务器的答案。

ma​​in.php

<?php
//**********************************************
//IF $_REQUEST CONTAINS pass_back this is an AJAX call, just send back and die.
if (array_key_exists('pass_back',$_REQUEST)) {
    echo $_REQUEST["pass_back"];
    die();
}
//***********************************************

echo '<html><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
    <script>
        function clickButton(currentId, nextId) {
            //alert(currentId+","+nextId); //check

            /*document.getElementById(currentId).style.display = "none";
            document.getElementById(nextId).style.display = "block";
            document.getElementById(nextId).style.border = "5px solid red";//check*/

            //**************************
            var xmlhttp;
            if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); }
            else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }

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

            xmlhttp.open("GET","testing.php?pass_back=pass_back",true);
            xmlhttp.send();
            //**************************

        }
    </script>
</head><body>';


//String of all the div's
$haystack = '<div id="div1" style="width:500px; height:250px; background-color:#fd77ba">Div1</div>
<div id="div2" style="width:500px; height:250px; background-color:#7781fd">Div2</div>
<div id="div3" style="width:500px; height:250px; background-color:#77fd9b">Div3</div>';

//Print all the divs
echo '<form method="post" enctype="multipart/form-data" accept-charset="utf-8">';
echo $haystack;
echo '<button type="button" onClick="clickButton(1,2)" style="font-family:Oxygen,sans-serif; font-style: normal;font-variant: normal;font-weight: normal;font-size: 99%;line-height: normal;font-size-adjust: none;font-stretch: normal; background-color: #494f50; color: #ffffff; padding-top: 5px;padding-right: 10px;padding-bottom: 5px; padding-left: 10px;margin-top: 50px;margin-right: 10px;margin-bottom: 50px;margin-left: 10px; text-decoration:none;">Submit</button>';
echo '</form>';
echo '</body></html>';
?>

祝你好运。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多