AJAX:如何在单击按钮时更改客户端和服务器端的值?

2023-12-13

在接下来的SSCCE中,

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

PROBLEM:

The currentIdnextId传递给按钮单击事件的 JS 事件监听器在名为的函数中计算returnCurrentId这需要$array_of_divs and $array_of_ids作为参数。然后它检查哪个div had style="display:none;"并将其设置为current_id。然后是它旁边的 id$array_of_ids成为next_id.

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

我的努力:

所以我一直在这里阅读 AJAX,并且尝试发送一个名为pass_back in the URL of XMLHTTPRequest.open(GET, URL, TRUE),并在服务器端尝试检查 $_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>';
?>

扎拉(Zarah),一些可能对您有帮助的想法:

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

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

对于类似的东西:

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

考虑到这是到您的网络服务器中名为testing.php的文件的有效路由。 open() 方法的 url 参数必须是某个文件的地址server并且您必须使用有效的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您可以找到有关该主题的更多信息。

EDIT

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

main.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>';
?>

祝你好运。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

AJAX:如何在单击按钮时更改客户端和服务器端的值? 的相关文章

随机推荐

  • 分层抽样 - 观察不足

    我想要实现的是从每组中获取 10 的样本 这是 2 个因素的组合 新近度和频率类别 到目前为止我已经考虑过包裹sampling和功能strata 这看起来很有希望 但我收到以下错误 并且很难理解错误消息以及错误所在或如何解决此问题 这是我的
  • 如何卸载新 WooCommerce 2.3.x 加载的 select2 脚本/样式?

    我们是主题开发人员 我们已经使用 select2 http select2 github io 我们的 WordPress 主题中 HTML 中的 SELECT 框的脚本 刚刚发布的新 WooCommerce 2 3 x 现在也使用 sel
  • MSChart / Asp.net 图表不显示工具提示

    我有一个仪表板页面 我在其中使用各种 MSCharts 我为每个图表定义了一个类 当我运行每个图表类并定义其系列属性时 我在该图表中定义系列的工具提示 如下所示 Series 0 ToolTip Date VALX d nTotal Qty
  • ICommand CanExecuteChanged 未更新

    我正在尝试 MVVM 模式基础级别 并对 ICommand CanExecute 更改感到震惊 我的 XAML 绑定如下
  • 调整图像亮度

    对于 Windows Phone 应用程序 当我通过滑块调整亮度时 它工作正常 将其移至右侧 但是当我回到之前的位置时 图像不是变暗 而是变得越来越亮 这是我基于像素操作的代码 private void slider1 ValueChang
  • SQL / MySQL - 按列长度排序

    在 MySQL 中 有没有办法按列的长度 字符 对结果进行排序 例如 myColumn lor lorem lorem ip lorem ips lorem ipsum 我想首先按最小的列长度 lor 对结果进行排序 然后以最大的列长度 l
  • 为什么析构函数挂起

    下面的代码工作正常 但是 当我启用p b in GetValue 代码失败 调试断言失败 为什么 class A int p public A p nullptr A if p nullptr delete p void GetValue
  • 如何为 json 负载定义 swagger 注释

    如何为此示例定义 swagger 注释 API TenantConfiguration 作为 json 负载获取 Consumes application json application xml POST public Message c
  • 本地主机上跨子域的用户身份验证

    我正在我的本地主机上构建一个应用程序 当我通过一个子域 例如 sub localhost 登录时 我需要在应用程序的所有其他子域 例如 sub2 localhost sub3 localhost 中使用 Auth 访问该登录用户 我将其更改
  • Pandas 风格:在整行上绘制边框,包括多索引

    我在 jupyter 笔记本中使用 pandas 样式来强调此数据框中子组之间的边界 从技术上讲 在每个更改的多重索引处绘制边框 但忽略最低级别 some sample df with multiindex res np repeat re
  • wordnet getDict() 找不到 Wordnet 词典

    当使用以下代码使用 WordNet 中的 Lemmatizer 算法时 gt initDict C Program Files x86 WordNet 2 1 dict 1 TRUE if initDict C Program Files
  • 在 Python 中将多字节字符转换为 7 位 ASCII

    我正在通过 Python 脚本下载并解析网页 我需要它 被编码为 7 位 ASCII 以便进一步处理 我正在使用 请求库 http docs python requests org en master 在一个 virtualenv 基于 U
  • 如何在 ListView 中访问 WebView 的 NavigateToString 属性

    我有一个ListView除其他外 其中包含WebView 当一个ListViewItem在此列表中被选中 我想将 HTML 绑定到WebView通过NavigateToString方法 WebView 需要位于绑定列表中 因为它绑定到项目列
  • 将本地 PDF 文件加载到 WebView 中

    我正在尝试将以下功能放入我正在编写的 iOS 应用程序中 在 XCode 中的项目的资源文件夹中发送一组 PDF 将 PDF 复制到应用程序目录 在网络视图中打开 PDF 据我所知 前两个步骤工作正常 我在复制操作后使用 FileManag
  • 使用 WPF WriteableBitmap.BackBuffer 绘制线条

    您是否知道任何库提供使用 WPF WriteableBitmap 和理想情况下 BackBuffer 绘制简单形状 线条和可选的其他形状 的方法 我知道有一个针对 silverlight 的 WriteableBitmapEx 项目 但是有
  • 如何使用 VBA 代码添加新电子表格

    我正在创建一个宏 宏的部分功能是让 VBA 创建一个新的电子表格 由于发行的性质 名称将会改变 我需要向此电子表格添加代码 无论如何我可以做到这一点吗 乔克已经解释了它是如何工作的 我会更进一步 添加工作表的语法是 expression A
  • /YYYY/MM/Title-Slug URL 结构与Friendly_Id 解决方案在#edit 上阻塞

    根据我得到的指导先前的问题在解决我的实现 YYYY MM Slug URL 结构的原始问题 我希望得到一些帮助来解决我在尝试编辑帖子时收到的错误 没有路由匹配 PATCH blog 2015 09 example post blog 201
  • 如何在android jdk中动态地用ImageView填充TableLayout?

    I ve a TableLayout我的元素main xml
  • ajax文件上传

    我正在努力在不重新加载页面的情况下上传 处理和显示文件 我该如何使用 jquery 将文件正确发布到服务器
  • AJAX:如何在单击按钮时更改客户端和服务器端的值?

    在接下来的SSCCE中 我有一个字符串 其中包含三个的 HTMLdivs I add a style display none 归因于所有div除了第一个之外 我给所有的按钮添加了一个按钮divs除了最后一个 并添加一个JSonclick事