如何使用jQuery进行AJAX调用?

时间:2019-02-09 05:00:58

标签: javascript jquery ajax

我正在处理需要从用户那里收集数据并显示在同一页面上的项目。我已经使用JavaScript成功完成了Ajax调用,但是现在我想使用Jquery。

这是我的JavaScript代码:

var output1 = document.getElementById("output1");

function saveUserInfo() {
  var userName = document.getElementById('username').value;
  var password = document.getElementById('password').value;
  var firstName = document.getElementById('firstname').value;
  var lastName = document.getElementById('lastname').value;
  var email = document.getElementById('email').value;
  var dob = document.getElementById('datepicker').value;
  var vars = "username=" + userName + "&password=" + password + "&firstname=" + firstName + "&lastname=" + lastName + "&email=" + email + "&datepicker=" + dob;

  var ajax = new XMLHttpRequest();
  var url = 'register.jsp';
  ajax.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      output1.innerHTML = (ajax.responseText);
    }
  }
  ajax.open("POST", url, true);
  ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  ajax.send(vars);
}

这是我的register.jsp:

<%@ page import ="java.sql.*" %>
<%@ page import ="javax.sql.*" %>


<%
String user = request.getParameter("username");

session.putValue("username",user);
String pwd = request.getParameter("password");
String fname = request.getParameter("firstname");
String lname = request.getParameter("lastname");
String email = request.getParameter("email");
String dob = request.getParameter("dob");

Class.forName("com.mysql.jdbc.Driver");

Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/user_info2","root","root");

Statement st = con.createStatement();
ResultSet rs;

//int i=st.executeUpdate("insert into user_info value('"+user+"','"+pwd+"','"+fname+"','"+lname+"','"+email+"')");

int i=st.executeUpdate("INSERT INTO `users`(user,pwd,fname,lname,email,dob) VALUE ('"+user+"','"+pwd+"','"+fname+"','"+lname+"','"+email+"','"+dob+"')");
 %>



Registration is Successfull. Welcome <%=user %>,
Your Password is : <%=pwd %>, 
FirstName : <%=fname %>, 
LastName : <%=lname %>, 
Email : <%=email %>, 
and Date Of Birth is :  <%=dob %>,

6 个答案:

答案 0 :(得分:1)

这是jQuery ajax请求的一般视图。

$.ajax({
    url: 'register.jsp',
    type: 'POST',
    data : {userName : userName,password: password,....},
    contentType: 'yourConentType', // ConentType that your are sending. No contentType needed if you just posting as query string parameters.
    success: function(response){
        // do whatever you want with response
     },
    error: function(error){
      console.log(error)
    }
});

如果您要将值作为对象传递,则如下:

var formData = {userName : userName, password: password,...};
$.ajax({
    url: 'register.jsp',
    type: 'POST',
    data : JSON.stringify(formData),
    contentType: 'application/json',
    success: function(response){
        // do whatever you want with response
     },
    error: function(error){
      console.log(error)
    }
});

有关更多详细信息:jQuery.ajax()

答案 1 :(得分:1)

function saveUserInfo() {
    var postData = {
        username: $('#userName').val(),
        password: $('#firstname').val(),
        firstName: $('#ss_unit').val(),
        lastName: $('#lastname').val(),
        email: $('#email').val(),
        dob: $('#datepicker').val()
    };

    $.post(url, postData).done(function(data) {
        output1.innerHTML = data;
    });
}

答案 2 :(得分:1)

您可以将jQuery的$.post方法与.fail.done一起使用。然后,您还可以使用查询的选择器从所有输入中获取值。

类似以下内容:

var output1 = $("#output1");

function saveUserInfo() {
  var userName = $('#username').val();
  var password = $('#password').val();
  var firstName = $('#firstname').val();
  var lastName = $('#lastname').val();
  var email = $('#email').val();
  var dob = $('#datepicker').val();

  var data = {userName, passWord, firstName, lastName, email, dob};

  var url = 'register.jsp';
  $.post(url, data)
    .done(function(msg) { /* yay it worked */ });
    .fail(function(xhr, status, err) {
      output1.text(err);
    });
}

我还注意到您在代码中得到了很多输入字段。如果所有这些输入字段都位于一个表单中(例如,标识为formId,则可以使用$('#formId').serialize()为您创建vars字符串。您可以阅读有关{{ 3}}。

答案 3 :(得分:1)

$.ajax({
  type: "POST",
  url: url,
  data: data,
  dataType: dataType
}).done(function(){

}).fail(function(){

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

答案 4 :(得分:1)

您可以使用以下语法来使用jquery的ajax调用。 将其添加到页面的顶部以供jquery参考。

     <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

对于JS:

     function saveUserInfo() {
     $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "...",   // your api or url for fetching data
                    data: "..",   // your data coming from front end in json
                    dataType: "json",
                    success: function (data) {
                        // your action need to perform
                    },
                    error: function (result) {
                       // handle error
                    }
                });
     }

但是,不建议在客户端提供与连接或数据库相关的信息。为了从后端获取数据,建议为此创建一个API或Web服务。

您可以使用以下链接作为参考。

Web服务:https://www.c-sharpcorner.com/UploadFile/00a8b7/web-service/

WebAPI:https://www.tutorialsteacher.com/webapi/create-web-api-project

注意:这些都用于C#后端。如果您还有其他用途,请提及您的语言名称。

答案 5 :(得分:0)

这是您代码的jQuery语法

  function saveUserInfo() {
      var userName = $('username').val();
      var password = $('password').val;
      var firstName = $('firstname').val;
      var lastName = $('lastname').val;
      var email =$('email').val;
      var dob = $('datepicker').val;
      var vars = {'userName':userName ,'password':password ,'firstName':firstName ,'lastName':firstName ,'email':email ,'datepicker':dob }

      $.ajax(
      {
          url:'register.jsp',
          data:vars ,
          type:'POST'
          dataType : "json",
          contentType: "application/json; charset=utf-8",
          success:function(result)
          {
             code to use result here
          }
       });
    }