AJAX:如何更改客户端的值,以及服务器端上的按钮点击? [英] AJAX: How to change a value on client side as well as server side on button click?

查看:87
本文介绍了AJAX:如何更改客户端的值,以及服务器端上的按钮点击?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面SSCCE,

  1. 在我有一个包含HTML三个 DIV s的字符串。
  2. 我添加了一个风格=显示:无;属性,所有的 DIV 取值除了第一个
  3. 我添加一个按钮,所有的 DIV 取值除了最后一个,并添加JS 的onclick 事件监听器,这应该在当前 DIV 的样式属性更改为风格=显示:无;(电流 DIV ID 属性传递给JS函数)和下 DIV 的(这是 ID 也传递给JS功能)样式属性风格=显示:块;
  4. 我添加了一个提交按钮,最后 DIV 它提交的表格。我没有写的动作表格属性或任何事件侦听此按钮,因为这不是担心,现在
  5. 我打印div的。

问题:

currentId nextId 传递到按钮点击事件的JS事件侦听器的计算在名为 returnCurrentId 一个函数,它接受了 $ array_of_divs $ array_of_ids 作为参数。然后检查其 DIV 中有风格=显示:无;,并将其设置为 current_id 。然后在它旁边在id的 $ array_of_ids 变成了 NEXT_ID

的问题,即当JS改变了 DIV (胡)的 ID 活动的样式属性已经传递给它在客户端,并且在服务器侧没有什么变化。因此,在服务器端,这是相同的 $ array_of_ids 传递给 returnCurrentId 没有在显示属性的任何变化,所以同样的 ID S的第一和第二 DIV 返回。他们传递给JS,然后再次在同一 DIV 再次显示。

我的努力:

所以,我一直在读了AJAX在这里,我试图发送一个名为 pass_back 变量在网​​址 XMLHTT prequest.open(GET,网址,TRUE),并在服务器端,试图检查是否$ _REQUEST中含有它,当它的,我做同样的改变样式属性,但它似乎并没有包含它。

问:

我期待我的配售code块在错误的地方,但我在哪里把它。

因此​​,谁能给我一些提示/建议/解决方案?

 < PHP
回声'< HTML>< HEAD> <元的charset =UTF-8> < META NAME =视口内容=WIDTH =装置宽度,初始规模= 1.0>
    <脚本>
        功能clickButton(currentId,nextId){
            警报(currentId +,+ nextId); //检查

            的document.getElementById(currentId).style.display =无;
            的document.getElementById(nextId).style.display =块;
            的document.getElementById(nextId).style.border =5像素的纯红色; //检查

            // ***********
            VAR XMLHTTP;
            如果(window.XMLHtt prequest){XMLHTTP =新XMLHtt prequest(); }
            其他{XMLHTTP =新的ActiveXObject(Microsoft.XMLHTTP); }

            xmlhttp.open(GET,C:/xampp/htdocs/testing.php pass_back =?+pass_back,真正的);
            xmlhttp.send();
            // ***********

        }
    < / SCRIPT>
< /头><身体GT;';


//所有的div的一个String
$草垛='< D​​IV ID =div1的风格=宽度:500px的;高度:250像素;背景颜色:#fd77ba> Div1构成< / DIV>
< D​​IV ID =DIV2的风格=宽度:500px的;高度:250像素;背景颜色:#7781fd> Div2时< / DIV>
< D​​IV ID =DIV3的风格=宽度:500px的;高度:250像素;背景颜色:#77fd9b> DIV3< / DIV>';

//添加的div的DOM对象到一个数组
需要'C:\\ \\ XAMPP的htdocs \\ simple_html_dom.php;
$的HTML = str_get_html($草堆);
的foreach($基于HTML>找到('格')为$ DIV){
    $ array_of_divs [] = $ DIV;
}

从$ array_of_divs所有元素//提取的id属性,并加入到$ array_of_ids
的foreach($ array_of_divs为$ DIV){
    $ array_of_ids [] = $ div-> ID;
}

//添加样式=显示:无;物业给所有的div除第一个
为($ i = 1; $ I<计数($ array_of_divs); $ I ++){
    $ array_of_divs [$ i]  - >风格=显示:无;;
}

//字符串伪键导航到同一个页面和真正的按钮上的下一个div来导航到另一个页面
$ pseudo_btn ='<按钮式=按钮的onClick =clickButton(\''returnCurrentId($ array_of_divs,$ array_of_ids)'current_id']'\',\''returnCurrentId($ array_of_divs,$ array_of_ids。 )['NEXT_ID']'\')的风格=字体家庭:氧气,无衬线;字体风格:正常;字体变形:正常;字体重量:正常;字体大小:99%;行高:正常;字体大小调整:无;字体舒展:正常;背景颜色:#494f50;颜色:#FFFFFF;填充顶:5像素,填充右:10px的;填充底:5像素;填充左:10px的;的margin-top:50px​​的;缘右:10px的;保证金底:50像素;保证金左:10px的;文字修饰:无;>提交< /按钮>';
$ real_btn ='<跨度风格=背景颜色:红色;><输入类型=提交名称=提交值=提交的风格=字体家庭:氧气,无衬线;字体风格:正常;字体变形:正常;字体重量:正常;字体大小:99%;行高:正常;字体大小调整:无;字体舒展:正常;背景颜色:# 494f50;颜色:#FFFFFF;填充顶:5像素,填充右:10px的;填充底:5像素;填充左:10px的;的margin-top:50px​​的;缘右:10px的;保证金底:50像素;保证金 - 左:10px的;文字修饰:无;>< / SPAN>';

//添加$伪BTN到所有除最后一个分区此页面上,$ real_btn添加到最后一个DIV
$ last_id =结束($ array_of_ids);
为($ J = 0; $ J<计数($ array_of_ids); $ J ++){
    如果($ array_of_ids [$ J]!== $ last_id){
        $ array_of_divs [$ J]  - >的innerText = $ pseudo_btn;
    } 其他 {
        $ array_of_divs [$ J]  - >的innerText = $ real_btn;
    }
}

//打印所有的div
回声'<形式方法=邮报是enctype =的multipart / form-data的接收字符集=utf-8>';
的foreach($ array_of_divs为$格){回声$ DIV; }
回声'< /形式GT;';

// **************
//如果$ _REQUEST CONTAINS pass_back(即按键一直是当前和下一个DIV preSSED,更改显示prePERTY
如果(array_key_exists('pass_back',$ _ REQUEST)){
        的foreach($ array_of_divs为$ divs_el){
            如果($ divs_el-> ID == returnCurrentId($ array_of_divs,$ array_of_ids)current_id]){
                $ divs_el->风格=显示:无;;
            }否则,如果($ divs_el-> ID == returnCurrentId($ array_of_divs,$ array_of_ids)NEXT_ID]){
                $ divs_el->风格=显示:块;;
            }
        }
} 其他 {
    回声$ _REQUEST不包含pass_back;
}
// ************

//该函数返回其上显示当前div的标识。
功能returnCurrentId($ array_of_divs,$ array_of_ids){
    为($ C = 0; $℃下计数($ array_of_divs); $ C ++){
        $ style_value = $ array_of_divs [$ C]  - >风格;
        $ style_value = preg_replace('/ \ s + /','',$ style_value); //这消除了各种空白。
        如果(strpos($ style_value,显示:无')=== FALSE){
            $ current_id = $ array_of_divs [$ C]  - > ID;
            打破;
        }
    }
    $ current_position = array_search($ current_id,$ array_of_ids);
    $ NEXT_ID = $ array_of_ids [$ current_position + 1];
    $ array_to_pass =阵列('current_id'=> $ current_id,'NEXT_ID'=> $ NEXT_ID);
    返回$ array_to_pass;
}



回声'< /身体GT;< / HTML>';
?>
 

解决方案

Zarah,一对夫妇的想法,可以帮助你:

正如我在我的评论说,试图改变这一点:

  xmlhttp.open(GET,?C:/xampp/htdocs/testing.php pass_back =+pass_back,真正的);
 

这样的事情:

  xmlhttp.open(GET,testing.php pass_back =?+pass_back,真正的);
 

考虑到这是一个在你的Web服务器名为testing.php文件的有效途径。在open()方法的URL参数,必须是一个地址,一个服务器上的一个文件,你必须使用一个有效的网址指向该文件。

另一个想法。您可以使用此方法发送POST信息:

  xmlhttp.open(POST,testing.php,真正的);
xmlhttp.setRequestHeader(内容型,应用程序/ x-WWW的形式urlen codeD);
xmlhttp.send(回传=回传);
 

所以你可以尝试它使用POST而非GET来看看会发生什么派。它可能会抛出一些轻此事。

更多的东西。

这可能是由于你的PHP配置,$ _REQUEST不包含任何,而$ _GET一样。这可能是一个很好的理由来检查$ _GET,而不是$ _REQUEST。但是,如果你想使用$ _REQUEST,这里 你可以找到有关主题的更多信息

修改

下面code(根据你的)对我的作品(Debian的阿帕奇/ PHP 5.4)。我已经把所有的code在同一页上。我不很喜欢,但它只是指出,它的工作原理。 AJAX的部分将数据发送到main.php和mai​​n.php简单地发回它所接收。然后AJAX的部分简单地提醒来自服务器的应答。

main.php

 < PHP
// **************
//如果$ _REQUEST CONTAINS pass_back这是一个AJAX调用,只是发回而死亡。
如果(array_key_exists('pass_back',$ _ REQUEST)){
    回声$ _REQUEST [pass_back];
    死();
}
// ************

回声'< HTML>< HEAD> <元的charset =UTF-8> < META NAME =视口内容=WIDTH =装置宽度,初始规模= 1.0>
    <脚本>
        功能clickButton(currentId,nextId){
            //警报(currentId +,+ nextId); //检查

            /*document.getElementById(currentId).style.display =无;
            的document.getElementById(nextId).style.display =块;
            的document.getElementById(nextId).style.border =5像素的纯红色; //检查* /

            // ***********
            VAR XMLHTTP;
            如果(window.XMLHtt prequest){XMLHTTP =新XMLHtt prequest(); }
            其他{XMLHTTP =新的ActiveXObject(Microsoft.XMLHTTP); }

            xmlhttp.onreadystatechange =功能(){
              如果(xmlhttp.readyState == 4和&安培; xmlhttp.status == 200)
                {
                警报(xmlhttp.responseText);
                }
            }

            xmlhttp.open(GET,testing.php pass_back = pass_back?,真正的);
            xmlhttp.send();
            // ***********

        }
    < / SCRIPT>
< /头><身体GT;';


//所有的div的一个String
$草垛='< D​​IV ID =div1的风格=宽度:500px的;高度:250像素;背景颜色:#fd77ba> Div1构成< / DIV>
< D​​IV ID =DIV2的风格=宽度:500px的;高度:250像素;背景颜色:#7781fd> Div2时< / DIV>
< D​​IV ID =DIV3的风格=宽度:500px的;高度:250像素;背景颜色:#77fd9b> DIV3< / DIV>';

//打印所有的div
回声'<形式方法=邮报是enctype =的multipart / form-data的接收字符集=utf-8>';
回声$草垛;
回声'<按钮式=按钮的onClick =clickButton(1,2)的风格=字体家庭:氧气,无衬线;字体风格:正常;字体变形:正常;字体体重:正常;字体大小:99%;行高:正常;字体大小调整:无;字体舒展:正常;背景颜色:#494f50;颜色:#FFFFFF;填充顶:5像素,填充右: 10px的;填充底:5像素;填充左:10px的;的margin-top:50px​​的;缘右:10px的;保证金底:50像素;保证金左:10px的;文字修饰:无;>提交< /按钮>';
回声'< /形式GT;';
回声'< /身体GT;< / HTML>';
?>
 

祝你好运。

In the following SSCCE,

  1. I have a string which contains the HTML for three divs.
  2. I add a style="display:none;" attribute to all the divs except the first one.
  3. I add a button to all the divs except the last one, and add a JS onclick event listener, which should change the current div's style property to style="display:none;" (current div's id attribute passed to the JS function.) and the next div's (it's id is also passed to the JS function) style property to style="display:block;"
  4. I add a submit button to the last div which submits the form. I did not write the action attribute of the form or any event listener for this button because that's not the concern right now.
  5. I print the div's.

PROBLEM:

The currentId and the nextId passed to the JS event listener of the button click event are calculated in a function named returnCurrentId which takes the $array_of_divs and $array_of_ids as arguments. Then it checks which div had style="display:none;" and sets it as the current_id. Then the id next to it in the $array_of_ids becomes the next_id.

The problem arises when the JS changes the style property of the divs whose ids have been passed to it on the client side, and nothing changes on the server side. So on the server side, it is the same $array_of_ids being passed to returnCurrentId without any changes in the display properties, and so the same ids of the first and second div are returned. They are passed to JS, and then again the same div is displayed again.

MY EFFORT:

So I have been reading up on AJAX here, and I tried to send a variable named pass_back in the URL of XMLHTTPRequest.open(GET, URL, TRUE), and on the server side, tried to check if $_REQUEST contains it, and when it does, I make the same change to the style properties, but it does not seem to contain it.

QUESTION:

I anticipate I am placing the block of code on the wrong place, but then where do I put it.

So can anyone give me some tips/suggestion/solution?

<?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, a couple of ideas that might help you:

As I said in my comment, try to change this bit:

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

for something like:

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

taking into consideration that that's a valid route to a file called testing.php in your web server. The url parameter of the open() method, must be an address to a file on a server and you must use a valid URL that points to that file.

Another idea. You can send post information using this approach:

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

so you could try to send it using POST instead of GET to see what happens. It might throw some light into the matter.

More things.

It is possible that due to your php configuration, $_REQUEST doesn't contain anything whereas $_GET does. This could be a good reason to check $_GET instead of $_REQUEST. However, if you do want to use $_REQUEST, here you can find more info about the topic.

EDIT

The following code (based on yours) works for me (debian APACHE/php 5.4). I've put all the code on the same page. I don't like it very much but it's only to point out that it works. The AJAX part sends the data to main.php and main.php simply sends back what it receives. Then the AJAX part simply alerts the answer from the server.

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

Good luck.

这篇关于AJAX:如何更改客户端的值,以及服务器端上的按钮点击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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