如何使用ajax从服务器接收数据? [英] How to receive data back from server using ajax?

查看:58
本文介绍了如何使用ajax从服务器接收数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我有一个带有用户名文本框和提交按钮的表单。现在我想要的是,当用户在文本框中输入文本时,它应该获取文本框值并将用户名发送到服务器,以便服务器可以检查用户名是否被其他任何用户使用。我可以将文本值发送到服务器,但我不知道如何接收一些数据并将文本框边框变为红色并在用户名已被删除时弹出错误。

Basically I have a form with a username textbox and a submit button in it. Now what I want is that when the user input text in textbox it should get the textbox value and send the username to server so the server could check whether the username is taken by any other user or not. I could do sending the text value to server but I don't know how to receive back some data and turn the textbox border into red and pop an error if the username has been taken.

以下是获取文本值并将其发送到服务器的代码:

Here is my code for getting text value and sending it to server:

<!DOCTYPE html>

<html>
 <head>

<script src="../JquerySock.js"></script>
<meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1">    

<script>
  $(document).ready(function() {
      $('#Registeration_Username_box').on('input', function() {
        console.log('excuted input');
        postUsernameToServer();
    });
  });
  function postUsernameToServer() {
      var formData = {
                'username': $('input[name=UserName]').val(),
              };
              // process the form
              $.ajax({
                  type: 'POST', // define the type of HTTP verb we want to use (POST for our form)
                  url: '../postr', // the url where we want to POST
                  data: formData, // our data object
                  dataType: 'json', // what type of data do we expect back from the server
                  encode: true
                })
    }
</script>
 </head>
<body>

<div id="Registeration_Div" class="Registeration_Div">
    <div class="createnewaccount" id="createnewaccount">Create new account</div>
    <form class="Registration_Form" id="Registration_Form" action="../postr" method="POST">

        <span class="Usernameerror_spn" id="Usernameerror_spn">Username has been taken</span>
        <div id="Registeration_Username_DIV" class="Registeration_Username_DIV">
            <input type="text" id="Registeration_Username_box" class="Registeration_Username_box"
                placeholder="Username" name="UserName" maxlength="30" />
        </div>

    </form>
</div>

</body>
</html>

正如你所看到的,我的用户名文本框之前有一个span框,默认情况下是隐藏的,但是我如果用户被带走,则希望显示它。

As you can see I have a span box before my username textbox which by default is hidden, but I want it to be shown if the user has been taken.

推荐答案

好吧,首先关闭:

您要求数据类型为 JSON 。这意味着在服务器端(是PHP吗?),您必须首先将其转换为JSON对象。在PHP中,这将是

You are requiring the datatype to be JSON. This means on the server side (Is it PHP?) you have to translate it to a JSON object first. In PHP this would be

$data = array("username" => "bla", "taken" => "taken");
echo json_encode($data);

对于Java EE,您可以使用:( source

For Java EE you could use this: (source)

int spacesToIndentEachLevel = 2;
new JSONObject(jsonString).toString(spacesToIndentEachLevel);

使用 org.json.JSONObject (已构建)在JavaEE和Android中)
现在,你必须确保它只返回所需的 JSON 而没有别的,否则你会收到错误。

Using org.json.JSONObject (built in to JavaEE and Android) Now, you have to make sure it returns ONLY the required JSON and nothing else, or you'll get errors.

然后,要获得ajax调用中的反馈:

Then, to get the feedback within your ajax call:

function postUsernameToServer() {
  var formData = {'username': $('input[name=UserName]').val()};
              // process the form
              $.ajax({
                  type: 'POST', // define the type of HTTP verb we want to use (POST for our form)
                  url: '../postr', // the url where we want to POST
                  data: formData, // our data object
                  dataType: 'json', // what type of data do we expect back from the server
                  encode: true
                }).done(function(data){ //any name you put in as an argument here will be the json response string.
                   var username = data.username;
                   var taken = data.taken;

                   //check if username is taken
                   if(taken == "taken"){
                     //make input border red
                     $('.yourInput').css({"border-color": "red"});
                   }
                   else{
                     //make input border green
                     $('.yourInput').css({"border-color": "green"});
                   }
              }).error(function(errorData){
                //Something went wrong with the ajax call. It'll be dealt with here
              });;
    }

这篇关于如何使用ajax从服务器接收数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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