简体   繁体   English

使用ajax在JavaScript中提交和显示表单数据

[英]Using ajax to submit and display form data in JavaScript

I have been tasked with using my skills with HTML/CSS/JavaScript/jQuery to solve a block of code according to these requirements: 我的任务是根据以下要求结合使用HTML / CSS / JavaScript / jQuery的技能来解决代码块:

Requirements: - Use ajax via the add_user function to submit the user entered data. 要求:-通过add_user函数使用ajax提交用户输入的数据。
- You can assume the service will respond with 200 status. -您可以假定该服务将以200状态响应。
- Display an error in red at the top of the form when the add user service responds with success property with a value of false. -当添加用户服务的成功属性为false时,在窗体顶部以红色显示错误。 Use the error property as the message. 使用error属性作为消息。
- Display new users in the users list when the response returns a success property -当响应返回成功属性时,在用户列表中显示新用户
- Highlight the email input when a user enters an invalid email address. -当用户输入无效的电子邮件地址时,突出显示电子邮件输入。 Also, display the text "please enter a valid email address" in red. 另外,以红色显示文本“请输入有效的电子邮件地址”。
NOTE: The service will not provide this validation functionality, and will accept invalid emails. 注意:该服务将不提供此验证功能,并且将接受无效的电子邮件。

//example usage.
addUser('john', 'smith', function(response){
    console.log('response is: ' + JSON.stringify(response)); 
});

/*
################################### DO NOT MODIFY BELOW THIS LINE ##########
############################################################################
*/
// Add user service wrapper.
function addUser(username, email, callback) {
    var response;

    if(username === "Error"){
        response = JSON.stringify({
            success: false,
            error: "Error is not acceptable username."
        });
    } else {
        response = JSON.stringify({
            success: true,
            user: {
                username: username,
                email: email
            }
        });   
    }

    $.ajax({
        url: '/echo/json/',
        type: "post",
        data: {
            json: response
        },
        success: callback
    });
};

The following HTML applies: 以下HTML适用:

<h2>Add a User:</h2>
<form>
    <input type="text" name="username" placeholder="name">
    <input type="email" name="email" placeholder="email">
    <button>add user</button>
</form>
<h2>Users:</h2>
<ul id="users"></ul>

CSS: CSS:

body {
    font-family: Helvetica, Sans, Arial;
}
p, ul {
    padding: 10px;
}
ul {
    margin: 5px;
    border: 2px dashed #999;
}

OK, hopefully you're still with me. 好吧,希望你还和我在一起。 I have a strong understanding of Object-Oriented JavaScript, as well as jQuery, HTML, and CSS. 我对面向对象的JavaScript以及jQuery,HTML和CSS有深刻的理解。 However, I have very little experience with AJAX, and none with JSON syntax/application. 但是,我对AJAX的经验很少,对JSON语法/应用程序的经验也很少。 Therefore, some aspects of this project seem very straightforward to me, and I do not believe I need assistance in figuring them out. 因此,该项目的某些方面对我来说似乎很简单,我认为在解决这些问题时不需要帮助。 The things I already know how to do properly include: 我已经知道如何正确执行的操作包括:

  • Displaying an error in red above the form (retrieving the error information is a different story) 在表单上方以红色显示错误(检索错误信息是另一回事)
  • Displaying new users in the unordered list section 在无序列表部分显示新用户
  • Highlight the email input when an invalid email address is entered (using client-side validation) 输入无效的电子邮件地址时,突出显示电子邮件输入(使用客户端验证)

The issues I am having in understanding this project focus on submitting and retrieving the data that is entered in the form. 我在理解该项目时遇到的问题集中在提交和检索在表单中输入的数据。 It appears as though the function addUser() first defines the variable response with a 'String' data type version of an 'Object' that contains key:value pairs of 'success: boolean, error: string' or 'success: boolean, user: {username:string,email:string}' - Here is where I run into my first area of trouble... 似乎函数addUser()首先使用“对象”的“字符串”数据类型版本定义了变量响应,其中包含“成功:布尔值,错误:字符串”或“成功:布尔值,用户”的键:值对:{username:string,email:string}'-这是我遇到第一个麻烦的地方...

If the objects containing those key:value pairs are to be relied on for determining whether or not an error has occurred during validation, and to retrieve data such as error messages and strings associated with the username and email, it would make sense to keep them as actual objects, rather than 'stringified' objects. 如果要依靠包含那些key:value对的对象来确定在验证期间是否发生了错误,并且要检索诸如错误消息以及与用户名和电子邮件相关联的字符串之类的数据,则将它们保留下来是很有意义的。作为实际对象,而不是“字符串化”对象。 As strings, I do not know how to access the value of a property of that object. 作为字符串,我不知道如何访问该对象的属性值。 If they were objects, I could simply refer to them using dot notation and retrieve their properties' values. 如果它们是对象,我可以简单地使用点表示法引用它们并检索其属性的值。 (ie sampleObj.success or sampleObj.error) It seems as though JavaScript functions such as eval() and JSON.parse() would suffice to return these strings into proper objects, but I have no idea how to implement those functions properly. (即sampleObj.success或sampleObj.error)似乎eval()和JSON.parse()之类的JavaScript函数足以将这些字符串返回到适当的对象中,但是我不知道如何正确实现这些函数。

The second major issues I am experiencing relates to the jQuery call of the .ajax() method. 我遇到的第二个主要问题与.ajax()方法的jQuery调用有关。 I have a very rudimentary understanding of how AJAX operates, but the syntax used here confuses me. 我对AJAX的运作方式非常初级,但是这里使用的语法使我感到困惑。 I understand that the data: {json:response} is being sent to the url:'/echo/json/' using the type:'post', but I do not understand how that data can be retrieved after this has taken place. 我知道数据:{json:response}正在使用类型:“ post”发送到url:'/ echo / json /',但是我不明白在发生这种情况后如何检索该数据。 I also do not understand what the value of 'response' is referring to in that process. 我也不清楚在此过程中“响应”的含义是什么。

Finally, I do not understand the use of a callback function at the end of the $.ajax() statement, and how it relates to the initial call of the addUser() function as a result of clicking the form button input. 最后,我不了解在$ .ajax()语句末尾使用回调函数的原因,以及单击表单按钮输入后它与addUser()函数的初始调用之间的关系。 I do not understand its purpose, or how it would be used syntactically. 我不了解其目的,也不了解如何在语法上使用它。

I understand this is a fairly complicated project, and I may be asking a lot. 我知道这是一个相当复杂的项目,我可能会提出很多要求。 But I have spent many hours over several days trying to make sense of this using my own knowledge and existing online resources, but have not gotten very far despite my diligence. 但是我花了几天时间,花了很多时间试图利用我自己的知识和现有的在线资源来理解这一点,但是尽管我很努力,但还没有走得很远。 I hope someone can assist me in understanding this example. 我希望有人可以帮助我理解这个例子。

A link to a live version of this project (jsfiddle.net) 指向该项目的实时版本的链接(jsfiddle.net)

//EDIT// An updated link to the jsfiddle workflow, with correct jQuery selectors and additional functionality for displaying error messages / user input: http://jsfiddle.net/brianjsullivan/5vv5w/ //编辑// jsfiddle工作流的更新链接,带有正确的jQuery选择器和用于显示错误消息的附加功能/用户输入: http : //jsfiddle.net/brianjsullivan/5vv5w/

The problem is that you forget the # (id) in your code: 问题是您忘记了代码中的# (id):

JSFIDDLE JSFIDDLE

$(document).ready(function(){
    $('#button').click(function(){
        $userInput = $('#username').val();
        $emailInput = $('#email').val();

        addUser($userInput,$emailInput,function(response){
            $('#users').html(JSON.stringify(response));
        });
    });    
});

Change your code to 将您的代码更改为

$(document).ready(function(){
 $('#button').click(function(){
    $userInput = $('#username').val();
    $emailInput = $('#email').val();

    addUser($userInput,$emailInput,function(response){
        $('#users').html(JSON.stringify(response));
    });
 });
});

Here is Fiddle . 这是小提琴

The JSON/string issue is a matter of a little experimentation/familiarity with JSON and JSON objects, but requires tons of explanation in lieu of a little testing, so I will focus on parts 2 and 3 of your question. JSON / string问题只是对JSON和JSON对象进行一些试验/熟悉而已,但是需要大量解释来代替一些测试,因此,我将重点介绍问题的第2部分和第3部分。 Perhaps someone else is better able than I to address the first part. 也许其他人比我更有能力解决第一部分。

An AJAX code block (1) Defines some variables with values, (2) Transmits them to a server-side script for processing, (3) Receives a response from the server. AJAX代码块(1)定义一些带有值的变量,(2)将它们发送到服务器端脚本进行处理,(3)接收来自服务器的响应。

The "old" construction (we now use the Promises interface) is the easiest way to envision how AJAX works: “旧的”构造(我们现在使用Promises接口)是设想AJAX如何工作的最简单方法:

$.ajax({
    type: "POST",
    url:  "pagename.php",
    data: "varName=" +varValue+ "&nextVarName=" + nextVarValue,
    success: function(returned_data) {
        //Var returned_data is ONLY available inside this fn!
        alert("Server said: " + returned_data);
    }
});

On the server side (using PHP for this example): 在服务器端(此示例使用PHP):

<?php

    $one = $_POST['varName'];  //$one contains varValue
    $two = $_POST['nextVarName'];  //$one contains nextVarValue

    //Do something with the received data, for eg a MySQL lookup

    $result = mysql_result(mysql_query(some lookup),0);

    $out = '<h1>Server says:</h1>';
    $out .='<p>For the purpose of this test, the server sends back:</p>';
    $out .= $result;

    echo $out;  //NOTE: uses echo, not return

Whatever the server side sends to the browser is received as the contents of the variable we have named returned_data . 无论服务器端发送到浏览器内容是什么,我们都会将其命名为returned_data

Note that we must deal with that variable ONLY inside the success function. 注意,我们只能在成功函数中处理该变量。 If we need access to it later on, we can either save the contents into global vars, or inject the data into a hidden DOM element, or ... 如果以后需要访问它,可以将内容保存到全局变量中,也可以将数据注入到隐藏的DOM元素中,或者...

These days, though, you want to use the promises interface -- which essentially does the same stuff, but not as clear for the purpose of explanation in an SO post. 但是,如今,您希望使用promises接口-本质上是做同样的事情,但是对于SO帖子中的解释目的并不清楚。 See below: 见下文:

Sources: 资料来源:

Kevin Chisholm on jQuery Promise Interface Kevin Chisholm在jQuery Promise界面上
jQuery 4 U jQuery 4 U
Daniel Demmel on Promises 丹尼尔·德梅尔(Daniel Demmel)谈诺言
José F. Romaniello 何塞·罗曼尼洛

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM