阿贾克斯变量值的JavaScript [英] Ajax variable value to javascript

查看:87
本文介绍了阿贾克斯变量值的JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直对一个问题,几个小时没有发现任何问题...

I've been on a problem for hours without finding any issue...

我必须为用户创建帐户登记表。当提交按钮是pressed一个validateForm函数被调用。

I have a registration form for users to create accounts. When the submit button is pressed a validateForm function is called.

在这个功能我做了一些工作的JavaScript测试,但我需要验证用户名可用。为此,我创建了一个外部的PHP文件,并使用$就调用它。

In this function I do some javascript tests that work, but then I need to verify that the username is available. For this I created an external PHP file and call it using $.ajax.

这里是code部分:

function validateRegistration(){
// Some tests....

// Check if username is already used
// Call external php file to get information about the username
$.ajax({
    url: 'AjaxFunctions/getUsernameAjax.php',
    data: "username=" + $("#username").val(),
    success: function(data){
        // Username already in use
        if(data == "ko"){
            // Stop validateForm()
        }
        // Username not used yet
        else{
            // Continue tests
        }
    }
});
// Other tests
}

我的问题是如何让validateForm()返回false从里面$阿贾克斯? 我如能在阿贾克斯部分之前声明JS变量,使用Ajax设置呢?

My question is how can I make validateForm() return false from inside the $.ajax ? Could I for instance declare a js variable before the Ajax part and set it with Ajax ?

我想答案是显而易见的,但我绝对新的Ajax,我不能让它...

I guess the answer is obvious but I'm absolutely new to Ajax and I can't get it...

非常感谢您的帮助!

推荐答案

要实现这一目标,你既可以做一个同步的Ajax调用像<一个描述href="http://stackoverflow.com/questions/133310/how-can-i-get-jquery-to-perform-a-synchronous-rather-than-asynchronous-ajax-re">this回答,但是这东西是令人难以置信的危险的,你的网站的性能。

To achieve this you can either do a synchronous ajax call like described in this answer, but that's something which is incredibly dangerous for the performance of your website.

另外 - 这是正确的方式 - 你应该有一个外部变量的用户名是否可用,只要用户输入你的要求的东西,如果它是有效的,你改变的变量,否则你显示一个警告消息。接下来,在你的validateRegistration()函数只检查外部变量(+可能的某种形式的回调,这取决于你叫吧)。是用户还是可以继续做的事情(如填写表格的其余部分),而该请求的优点正在等待。

Alternatively - and this is the right way - you should have an external variable whether the username is available, as soon as the user inputs something you do the request and if it's valid you change the variable otherwise you show an warning message. Next in your validateRegistration() function you only check the external variable (+ possible some form of callback, depending on where you call it from). The advantage being that the user can still continue doing things (like filling out the rest of the form) whilst the request is pending.

这篇关于阿贾克斯变量值的JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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