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

Javascript AJAX:如何在点击按钮时更改客户端和服务器端的值?,javascript,php,html,ajax,xmlhttprequest,Javascript,Php,Html,Ajax,Xmlhttprequest,在以下SSCCE中 我有一个字符串,其中包含三个divs的HTML 我向所有divs添加一个style=“display:none;”“属性,第一个除外 我在所有的div中添加了一个按钮(最后一个除外),并添加了一个JSonclick事件监听器,它应该将当前div的style属性更改为style=“display:none;”“(当前div的id属性传递给JS函数)和下一个div(它的id也传递给JS函数)style属性到style=“display:block;” 我在提交表单的最后一个div

在以下SSCCE中

  • 我有一个字符串,其中包含三个
    div
    s的HTML
  • 我向所有
    div
    s添加一个
    style=“display:none;”“
    属性,第一个除外
  • 我在所有的
    div
    中添加了一个按钮(最后一个除外),并添加了一个JS
    onclick
    事件监听器,它应该将当前
    div
    的style属性更改为
    style=“display:none;”“
    (当前
    div
    id
    属性传递给JS函数)和下一个
    div
    (它的
    id
    也传递给JS函数)style属性到
    style=“display:block;”
  • 我在提交
    表单的最后一个
    div
    中添加了
    submit
    按钮。我没有为该按钮编写
    表单的
    action
    属性或任何事件侦听器,因为这不是现在的问题
  • 我打印部门的
  • 问题: 传递给按钮点击事件的JS事件监听器的
    currentId
    nextId
    在名为
    returnCurrentId
    的函数中计算,该函数将
    $array\u of_divs
    $array\u of_id
    作为参数
    并将其设置为
    当前\u id
    。然后在
    $array\u\u\u id
    中它旁边的id将成为
    下一个\u id

    当JS更改
    div
    s的style属性时会出现问题,该div的
    id
    s已在客户端传递给它,而在服务器端没有任何更改。因此,在服务器端,相同的
    $array\u of_id
    被传递给
    returnCurrentId
    ,显示属性没有任何更改,因此,返回第一个和第二个
    div
    的相同
    id
    s。它们被传递给JS,然后再次显示相同的
    div

    我的努力: 所以我一直在这里阅读AJAX,我试图在
    XMLHTTPRequest.open的
    URL
    中发送一个名为
    pass\u back
    的变量(GET,URL,TRUE)
    ,在服务器端,尝试检查$\u请求是否包含它,当它包含时,我对样式属性进行了相同的更改,但它似乎不包含它

    问题: 我预计我将代码块放在了错误的地方,但是我应该把它放在哪里呢

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

    <?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);
    
    考虑到这是指向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发送,而不是去看发生了什么。这可能会给事情带来一些启示

    更多的事情

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

    编辑

    下面的代码(基于您的代码)适合我(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>';
    ?>
    

    这是一种不好的项目处理方式。您可以使用PHP构建原始HTML页面,但除非您从数据库中获取信息,或者有大量重复代码,否则只需将HTML和JavaScript分开。您的JavaScript应该位于外部页面上,因此它会缓存到浏览器内存中。如果您必须步行您自己页面上的DOM,而不是使用PHP使用JavaScript。您可以简单地拥有一个HTML类属性,该属性受CSS影响,而不是使用PHP创建的HTML进行样式设置。如果您需要在事件发生时进行样式设置,则使用JavaScript。在您的使用中,AJAX用于将数据发送到通常不同的PHP页面。您可以使用
    $\u GET['property']
    获取$\u get url的
    部分,该部分显示如下:
    ?property=value&prop=val
    。换句话说,在PHP页面上用
    xhr.open('get','here.PHP?property=value&prop=val')指定的
    之后
    。在
    xhr.status==200&&readyState==4
    时,通常不会将HTML发送回JavaScript
    onreadystatechange
    中。在使用PHP页面进行响应时,通常会将信息存储在PHP关联数组中,您可以
    回送json\u编码($arrayHere);
    @zarah我想你应该在这一位放一个有效的HTTP URL:xmlhttp.open(“GET”,“C:/xampp/htdocs/testing.php?pass_back=“+”pass_back“,true);尝试使用类似c://的东西不是有效的协议
    @Zarah
    ,看起来您可以添加
    ,并且您可能可以将CSS页面放在文件夹中,对吧?那么您应该这样做。您可以将AJAX发送到同一页面,但随后必须向页面添加一组PHP代码,以确保初始状态和AJAX状态不同租金。换句话说,添加一组PHP条件,这样你就不会得到一个JSON响应,其中包含你已经用来制作页面的HTML代码。最后,
    C:/xampp/htdocs/testing.PHP
    可能应该是
    localhost/testing.PHP
    。了解以下内容很重要:当你将URL放入浏览器地址栏时,服务器看起来塞