困惑的AJAX的基础知识 [英] Confused on the basics of AJAX

查看:129
本文介绍了困惑的AJAX的基础知识的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以现在,我只是用一种基本形式来检查密码。我想它来检查密码,并基本保持在page.html即可,所以我可以使用JavaScript来提醒密码不正确或东西。我真的不知道该怎么做。现在看来,这会给我带来给check.php。我不太确定的整个过程,任何帮助AP preciated!谢谢!

page.html即可

 <形式的行动=check.php方法=邮报>
    <输入类型=密码NAME =密码/>
    <输入类型=提交值=提交/>

< /形式GT;
 

check.php

 < PHP
    $密码= $ _ POST ['密码'];
    如果($的密码!=测试){
        死();
    }
?>
 

解决方案

PHP运行在通常运行在的物理上不同的的机器(服务器端)(Web服务器比web浏览器运行在客户端侧)。该机器通常通过网络连接。 HTTP是一个网络协议。 web浏览器发送一个HTTP请求。 Web服务器检索其URL表明它应该被转发到PHP作进一步处理一个HTTP请求。 PHP检索的HTTP请求和所进行的处理,并返回一个HTTP响应。通常在一个普通的HTML页面的味道。 Web服务器发送HTTP响应返回给web浏览器。

JavaScript的运行在web浏览器和一无所知PHP,因为它运行在网络服务器。 PHP反过来也一无所知的JavaScript(尽管它可以的制作的一些JS code后者又被发送到web浏览器通过HTTP)。 JS和PHP之间进行通信的唯一方法是HTTP。其中一个方法,让JS火HTTP请求和检索使用 <$ C HTTP响应$ C> XMLHtt prequest 。这背后是阿贾克斯的核心技术。

我看到你的问题的历史,你已经熟悉了 jQuery的。这是一个JS库有很多方便的功能火ajaxical请求。你会在这种特殊情况下要使用 $。交 。例如,

  $('#formId)。递交(函数(){
    .post的$('check.php',$(本).serialize(),功能(有效){
        如果(有效){
            警报(有效!);
        } 其他 {
            警报(无效的!);
        }
    });
    返回false; // 重要!该块表的默认操作。
});
 

随着 check.php

 &LT; PHP
    回声$ _ POST ['密码'] =测试!;
?&GT;
 

这不过是不不显眼。如果用户已经JS的禁用,则都将失败。最好的办法是检查在PHP如果ajaxical请求被解雇或用jQuery的不和相应的处理:

 如果($ _ SERVER ['HTTP_X_REQUESTED_WITH'] =='XMLHtt prequest'){
    //阿贾克斯。
} 其他 {
    //没有AJAX。
}
 

另外,您可以让jQuery的也达到不同的URL或附加额外的参数。


更新:这里是JavaScript将如何看时,不使用jQuery这样的:

 的document.getElementById('formId')。的onsubmit =功能(){
    VAR XHR =(window.XMLHtt prequest)?新XMLHtt prequest():新的ActiveXObject(Microsoft.XMLHTTP);
    xhr.onreadystatechange =功能(){
        如果(xhr.readyState == 4和&安培; xhr.status == 200){
            如果(xhr.responseText){
                警报(有效!);
            } 其他 {
                警报(无效的!);
            }
        }
    }
    xhr.open('POST','check.php,真正的);
    xhr.send(连载(本));
    返回false; // 重要!该块表的默认操作。
}

函数序列化(形式){
    VAR的查询='';
    对于(VAR I = 0; I&LT; form.elements.length;我++){
        变种E = form.elements [I]
        如果(e.disabled&安培;!&安培; e.name
            &功放;&安培; ((e.type ='复选框'和;!&安培;!e.type ='广播')|| e.checked)
            &功放;&安培; (e.type!='提交'||ē== document.lastClicked))
        {
            如果(query.length)查询+ ='和;';
            查询+ = e.name +=+ EN codeURIComponent(e.value);
        }
    }
    返回查询;
}

document.onclick =功能(E){
    Ë= E ||事件;
    document.lastClicked = e.target || e.srcElement;
}
 

臃肿冗长,是的;)

So right now, I'm just using a basic form to check a password. I want it to check the password and basically remain on page.html so I can use JavaScript to alert incorrect password or something. I'm not really sure how to do that. It seems it would bring me to check.php. I'm not too sure on the whole process, any help appreciated! Thanks!

Page.html

<form action="check.php" method="post">
    <input type="password" name="password" />
    <input type="submit" value="Submit" />

</form>

check.php

   <?php
    $password = $_POST['password'];
    if ( $password != "testing" ) {
        die();
    }
?>

解决方案

PHP runs at the webserver which usually runs at a physically different machine (the server side) than where the webbrowser runs (the client side). The machines are usually connected by a network. HTTP is a network protocol. The webbrowser sends a HTTP request. The webserver retrieves a HTTP request whose URL indicates that it should be forwarded to PHP for further processing. PHP retrieves the HTTP request and does the processing and returns a HTTP response. Usually in flavor of a plain vanilla HTML page. The webserver sends HTTP response back to the webbrowser.

JavaScript runs at the webbrowser and knows nothing about PHP since it runs at the webserver. PHP in turn also knows nothing about JavaScript (although it can produce some JS code which is in turn to be sent to the webbrowser over HTTP). The only way to communicate between JS and PHP is HTTP. One of the ways to let JS fire a HTTP request and retrieve a HTTP response is using XMLHttpRequest. This is the core technique behind Ajax.

I see in your question history that you're already familiar with jQuery. It's a JS library with a lot of convenient functions to fire ajaxical requests. In this specific case you would like to use $.post. E.g.

$('#formId').submit(function() {
    $.post('check.php', $(this).serialize(), function(valid) {
        if (valid) {
            alert('Valid!');
        } else {
            alert('Invalid!');
        }
    });
    return false; // Important! This blocks form's default action.
});

With in check.php:

<?php
    echo $_POST['password'] != "testing";
?>

This is however not unobtrusive. If the user has JS disabled, then all will fail. Your best bet is to check in PHP if an ajaxical request is been fired by jQuery or not and handle accordingly:

if ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
    // Ajax.
} else {
    // No ajax.
}

Alternatively you can let jQuery also reach a different URL or append an extra parameter.


Update: here is how the JavaScript would look like when not using jQuery:

document.getElementById('formId').onsubmit = function() {
    var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            if (xhr.responseText) {
                alert('Valid!');
            } else {
                alert('Invalid!');
            }
        }
    }
    xhr.open('POST', 'check.php', true);
    xhr.send(serialize(this));
    return false; // Important! This blocks form's default action.
}

function serialize(form) {
    var query = '';
    for(var i = 0; i < form.elements.length; i++) {
        var e = form.elements[i];
        if (!e.disabled && e.name 
            && ((e.type != 'checkbox' && e.type != 'radio') || e.checked)
            && (e.type != 'submit' || e == document.lastClicked))
        {
            if (query.length) query += '&';
            query += e.name + '=' + encodeURIComponent(e.value);
        }
    }
    return query;
}   

document.onclick = function(e) {
    e = e || event;
    document.lastClicked = e.target || e.srcElement;
}

Bloated and verbose, yes ;)

这篇关于困惑的AJAX的基础知识的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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