jQuery使用AJAX发送请求,以及回调函数对json格式数据的处理

======================================

首先讲一下SpringMVC只需要在Spring web容器总共为RequestMappingHandleAdapter装配处理JSON的HttpMessageConverter,并在交互过程中通过请求的Accept指定MINE类型,SpringMVC就可以使服务器的处理方法和客户端JSON格式的消息进行通信了。@RequestBody注解用于读取request请求的body部分数据,使用系统,默认配置的HttpMessageConverter进行解析,然后把相应的数据绑定到Controller中方法的参数上。。。总而言之,下面测试的例子就只需要把Jackson的jar包加进来,然后就可以使用@RequestBody注解了,如果使用的是Jackson,那么Spring的HttpMessageConverter会帮我们做默认配置,如果使用的是其他包解析json,那么需要在springmvc的配置文件中进行配置。。

废话有点多,直接看代码……

========================================

1.首先是测试环境的搭建,本例使用MAVEN+SpringMVC搭建基础环境

2.使用SpringMVC以及web项目所要的基本配置文件,以及maven的依赖管理pom.xml

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.lin</groupId>
  <artifactId>My_AJAX_Test</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>

<!-- 引入依赖的jar包 -->
  <dependencies>
  	
  	<!-- Spring Begin -->
	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-webmvc</artifactId>
	    <version>4.3.7.RELEASE</version>
	</dependency>
	<!-- Spring的面向切面编程 -->
	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-aspects</artifactId>
	    <version>4.3.7.RELEASE</version>
	</dependency>	
	<!-- Spring End -->
  	
  	<!-- jstl、servlet-api、junit -->
	<dependency>
	    <groupId>javax.servlet</groupId>
	    <artifactId>jstl</artifactId>
	    <version>1.2</version>
	</dependency>
  	
	<dependency>
	    <groupId>javax.servlet</groupId>
	    <artifactId>javax.servlet-api</artifactId>
	    <version>4.0.1</version>
	    <scope>provided</scope>
	</dependency>
 
	<dependency>
	    <groupId>junit</groupId>
	    <artifactId>junit-dep</artifactId>
	    <version>4.10</version>
	    <scope>test</scope>
	</dependency>
	
	<!-- jackson begin -->
	<dependency>
	    <groupId>com.fasterxml.jackson.core</groupId>
	    <artifactId>jackson-databind</artifactId>
	    <version>2.9.4</version>
	</dependency>
	<!-- jackson end -->
	
	
  </dependencies> 
  
</project>

springmvc-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	   xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
	   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	   xmlns:p="http://www.springframework.org/schema/p"
	   xmlns:mvc="http://www.springframework.org/schema/mvc"
	   xmlns:context="http://www.springframework.org/schema/context"
	   xmlns:tx="http://www.springframework.org/schema/tx"
	   xsi:schemaLocation="http://www.springframework.org/schema/beans
	   					   http://www.springframework.org/schema/beans/spring-beans.xsd
	   					   http://www.springframework.org/schema/mvc
	   					   http://www.springframework.org/schema/mvc/spring-mvc.xsd
	   					   http://www.springframework.org/schema/context
	   					   http://www.springframework.org/schema/context/spring-context.xsd
	   					   http://www.springframework.org/schema/tx
	   					   http://www.springframework.org/schema/tx/spring-tx.xsd
	   					   http://mybatis.org/schema/mybatis-spring
	   					   http://mybatis.org/schema/mybatis-spring.xsd">
 
 
	<!-- 自动扫描该包,SpringMVC会将包下用@Controller注解的类注册为Spring的controller -->
	<context:component-scan base-package="com.lin"/>
	
	<!--两个标准配置  -->
	<!-- 将springmvc不能处理的请求交给tomcat -->
	<mvc:default-servlet-handler/>
	<!-- 能支持springmvc更高级的一些功能,JSR303校验,快捷的ajax...映射动态请求 -->
	<mvc:annotation-driven/>
	
	<!-- 视图解析器 -->
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!-- 前缀 -->
		<property name="prefix">
			<value>/WEB-INF/content/</value>
		</property>
		<!-- 后缀 -->
		<property name="suffix">
			<value>.jsp</value>
		</property>
	</bean>
	
 
</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <display-name>My_AJAX_Test</display-name>
  
  <!-- 定义Spring MVC的前端控制器 -->
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring/springmvc-config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  
  <!-- 让Spring MVC的前端控制器拦截所有请求 -->
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  
  <!-- 编码过滤器 -->
  <filter>
	<filter-name>characterEncodingFilter</filter-name>
	<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
	<init-param>
		<param-name>encoding</param-name>
		<param-value>UTF-8</param-value>
	</init-param>
   </filter>
   <filter-mapping>
		<filter-name>characterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
 
</web-app>

=======================================

3.因为这里使用的是jQuery的AJAX,所以基础环境搭好以后加入jQuery的js库,自己百度下载去

========================================

4.写一个实体类

package com.lin.domain;

import java.io.Serializable;

public class Book implements Serializable {
	private static final long serialVersionUID = 1L;

	private Integer id;
	private String name;
	private String author;
	
	public Book() {
		super();
	}

	public Book(Integer id, String name, String author) {
		super();
		this.id = id;
		this.name = name;
		this.author = author;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

}

5.controller

package com.lin.controller;

import com.lin.domain.Book;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
 
@Controller
@RequestMapping("/json")
public class BookController {
	
	@RequestMapping("/testRequestBody")
	@ResponseBody//这个注解表示将以下方法的返回值自动转换成json格式的数据(记得要添加jackson的jar包(无需配置)或者其它的第三方json类库(需另外在springmvc配置文件中配置))
	public Book setJson(Book book){
		book.setAuthor("林");
		System.out.println(book);
		return book;
	}
 
}

6.然后就是页面,我们将页面设置成当页面加载完成时自动发起AJAX请求,当然你可以通过事件来发送。。

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>测试接收JSON格式的数据</title>
<script type="text/javascript" src="${request.getContextPath()}static/js/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
	$(document).ready(function(){
		testRequestBody();
	});
	
	function testRequestBody(){
		$.ajax({
			
			url:"${pageContext.request.contextPath}/json/testRequestBody",// 发送请求的URL字符串。
			// 发送到服务器的数据。
			data:{id : 1, name : "测试测试"},
	   		type : "post", //  请求方式 POST或GET
			dataType : "json", // 预期服务器返回的数据类型。
			async:  true , // 默认设置下,所有请求均为异步请求。如果设置为false,则发送同步请求
			// 请求成功后的回调函数。
			success :function(data){
				$("#id").html(data.id);
				$("#name").html(data.name);
				$("#author").html(data.author);
				
			},
			// 请求出错时调用的函数
			error:function(){
				alert("数据发送失败");
			}
		});
	}
</script>
</head>
<body>
	编号:<span id="id"></span><br>
	书名:<span id="name"></span><br>
	作者:<span id="author"></span><br>
</body>
</html>

=============================

测试结果:

 

==========================================

==========================================

下面测试解析集合的json数据

首先改下controller类

package com.lin.controller;

import com.lin.domain.Book;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
 
@Controller
@RequestMapping("/json")
public class BookController {
	
	@RequestMapping("/testRequestBody")
	@ResponseBody//这个注解表示将以下方法的返回值自动转换成json格式的数据(记得要添加jackson的jar包(无需配置)或者其它的第三方json类库(需另外在springmvc配置文件中配置))
	public List<Book> setJson(Book book){
		List<Book> list = new ArrayList<Book>();
		Book b1 = new Book(1,"AJAX从入门到精通","林");
		Book b2 = new Book(2,"Java编程思想","外国");
		list.add(b1);
		list.add(b2);
		return list;
	}
 
}

 

然后是改下页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>测试接收JSON格式的数据</title>
<script type="text/javascript" src="${request.getContextPath()}static/js/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
	$(document).ready(function(){
		testRequestBody();
	});
	
	function testRequestBody(){
		$.ajax({
			
			url:"${pageContext.request.contextPath}/json/testRequestBody",// 发送请求的URL字符串。
	   		type : "post", //  请求方式 POST或GET
			dataType : "json", // 预期服务器返回的数据类型。
			async:  true , // 默认设置下,所有请求均为异步请求。如果设置为false,则发送同步请求
			// 请求成功后的回调函数。
			success :function(data){
				console.log(data);
				for(var p in data){//遍历json数组时,这么写p为索引,0,1
					console.log(data[p].name + " " + data[p].author);
				}
			},
			// 请求出错时调用的函数
			error:function(){
				alert("数据发送失败");
			}
		});
	}
</script>
</head>
<body>
	编号:<span id="id"></span><br>
	书名:<span id="name"></span><br>
	作者:<span id="author"></span><br>
</body>
</html>

测试结果在页面按F12,看控制台

数据取到了,该怎么在页面显示那就不是问题了,处理一下就好了。。。

 

================================

==================================

==================================

粗浅的记录下,使用jQuery来发起AJAX请求,以及解析和接受的json数据的转换。。。

对了,这里要强调一下系统中web路径的问题,引用静态文件最好用${request.getContextPath()}方式,如下

<script type="text/javascript" src="${request.getContextPath()}static/js/jquery-1.12.4.min.js"></script>

或:  <script type="text/javascript" src="${pageContext.request.contextPath}/static/js/jquery-1.12.4.min.js"></script>

一开始我这样 src="/static/js/jquery-1.12.4.min.js",发现在eclipse中可以找的到对应的文件,然后一发布,js效果没有出来,然后发现应该是路径这边出了问题,所以以上只是建议。。。

还有就是发请求也同样。。。

 

 

这里附上一个jQuery设置标签中值的方法(这里直接使用的是W3School中的jQuery相关的知识)

<!DOCTYPE html>
<html>
<head>
<script src="/jquery/jquery-1.11.1.min.js"></script>
<script>
$(document).ready(function(){
  $("#btn1").click(function(){
    $("#test1").text("Hello world!");
  });
  $("#btn2").click(function(){
    $("#test2").html("<b>Hello world!</b>");
  });
  $("#btn3").click(function(){
    $("#test3").val("Dolly Duck");
  });
});
</script>
</head>

<body>
<p id="test1">这是段落。</p>
<p id="test2">这是另一个段落。</p>
<p>Input field: <input type="text" id="test3" value="Mickey Mouse"></p>
<button id="btn1">设置文本</button>
<button id="btn2">设置 HTML</button>
<button id="btn3">设置值</button>
</body>
</html>

结果:

 

=================================================

=================================================

=================================================

下面再附上一个实例,与上述差不多:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.lin</groupId>
  <artifactId>SpringMVCTest</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>

	<dependencies>
	  	<!-- spring begin -->
		<!--spring-core-->  
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-core</artifactId>
		    <version>4.2.0.RELEASE</version>
		</dependency>
		<!-- spring-web-mvc -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>4.2.0.RELEASE</version>
		</dependency>
		<!-- spring end -->
	
		<!-- jackson begin -->
		<dependency>
		    <groupId>com.fasterxml.jackson.core</groupId>
		    <artifactId>jackson-databind</artifactId>
		    <version>2.9.4</version>
		</dependency>
		<!-- jackson end -->
  	</dependencies>
 
</project>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <display-name>SpringTagTest</display-name>
  <!-- 定义Spring MVC的前端控制器 -->
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring/springmvc-config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  
  <!-- 让Spring MVC的前端控制器拦截所有请求 -->
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  
  <!-- 编码过滤器 -->
  <filter>
		<filter-name>characterEncodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
  </filter>
	<filter-mapping>
		<filter-name>characterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
</web-app>

springmvc-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                              http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
                              http://www.springframework.org/schema/mvc
                              http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
                              http://www.springframework.org/schema/context
                              http://www.springframework.org/schema/context/spring-context-4.2.xsd
                              http://www.springframework.org/schema/tx
                              http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
                              http://mybatis.org/schema/mybatis-spring
                              http://mybatis.org/schema/mybatis-spring.xsd">
 
    <!-- 自动扫描该包,SpringMVC会将包下用@Controller注解的类注册为Spring的controller -->
    <context:component-scan base-package="com.lin"/>
    
    <!-- 设置默认配置方案 -->
    <mvc:annotation-driven/>
    
	<!-- 使用默认的Servlet来响应静态文件 -->
	<mvc:default-servlet-handler/>
	
    <!-- 视图解析器 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 前缀 -->
        <property name="prefix">
            <value>/WEB-INF/content/</value>
        </property>
        <!-- 后缀 -->
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
 
</beans>

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>首页</title>
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/jquery-1.12.4.min.js"></script>
<%-- <script type="text/javascript" src="${request.getContextPath()}static/js/jquery-1.12.4.min.js"></script> --%>
<script type="text/javascript">
	//$(document).ready(function(){
	$(function(){
	
		$("#submit").click(function(){
			testRequestBody();
		});
		
		function testRequestBody(){
			$.ajax({
				
				url:"${pageContext.request.contextPath}/ajaxTest",// 发送请求的URL字符串。
				// 发送到服务器的数据。
				data:{username : $("#username").val(), sex : $("#sex").val(), password : $("#password").val()},
		   		type : "post", //  请求方式 POST或GET
				dataType : "json", // 预期服务器返回的数据类型。
				async:  true , // 默认设置下,所有请求均为异步请求。如果设置为false,则发送同步请求
				// 请求成功后的回调函数。
				success :function(data){
					$("#username").val(data.username);
					$("#sex").val(data.sex);
					
				},
				// 请求出错时调用的函数
				error:function(){
					alert("数据发送失败");
				}
			});
		}
		
	});
	
</script>
</head>
<body>
	<div align="center">
		<table align="center">
			<tr>
				<td align="center">用户名:</td>
				<td align="center"><input type="text" id="username" name="username"></td>
			</tr>
			
			<tr>
				<td align="center">性别:</td>
				<td align="center"><input type="text" id="sex" name="sex"></td>
			</tr>
			
			<tr>
				<td align="center">密码:</td>
				<td align="center"><input type="text" id="password" name="password"></td>
			</tr>
			
			<tr>
				<td colspan="2"><input type="submit" id="submit" value="提交"></td> 
			</tr>
		</table>
	</div>
</body>
</html>

AJAXControllerTest.java

package com.lin.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lin.domain.User;

@Controller
public class AJAXControllerTest {

	@RequestMapping("ajaxTest")
	@ResponseBody
	public User ajaxTest(User user,HttpServletRequest request,HttpServletResponse response){
		
		System.out.println(user.getUsername());
		System.out.println(user.getSex());
		System.out.println(user.getPassword());
		
		User u = new User();
		u.setUsername("小杨");
		u.setSex("女");
		
		return u;
		
//		System.out.println(username);
//		System.out.println(sex);
		
	}
	
}

User.java

package com.lin.domain;

public class User {

	private String username;
	private String sex;
	private String password;
	
	
	public User() {
		super();
	}
	
	public User(String username, String sex, String password) {
		super();
		this.username = username;
		this.sex = sex;
		this.password = password;
	}
	
	@Override
	public String toString() {
		return "User [username=" + username + ", sex=" + sex + ", password="
				+ password + "]";
	}

	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
}

测试结果:

1.填写表单:

2.1点击提交后控制台:

2.2点击提交后表单页面:

==========================

如果不使用jackson或者其他的一些处理json数据的jar包,那么就自己构造json格式的数据返回给前台也行,可以参考手动构造json格式的方式。。

以下不贴出全部代码,因为跟上面这个例子一模一样,只需改下controller即可(pom中的jackson依赖也可以去掉,不影响了):

package com.lin.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lin.domain.User;

@Controller
public class AJAXControllerTest {
	
	@RequestMapping("ajaxTest")
//	@ResponseBody
	public void ajaxTest(User user,HttpServletRequest request,HttpServletResponse response) throws IOException{
		
		System.out.println(user.getUsername());
		System.out.println(user.getSex());
		System.out.println(user.getPassword());
		
		User u = new User();
		u.setUsername("小杨");
		u.setSex("女");
		
		StringBuilder sBuilder = new StringBuilder();
		
		sBuilder.append("{\"username\":\""+"小杨"+"\",\"sex\":\""+"女"+"\"},");
		sBuilder.deleteCharAt(sBuilder.length()-1);
		
//		return u;
		System.out.println(sBuilder);
		//设置响应编码(这里有个问题就是,我明明在web.xml中配置了编码过滤器,但是这里如果不再设置响应编码还是会乱码。。。。)
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(sBuilder.toString());
		
	}
	
}

结果与上面的例子同。。。。。这里要注意一下就是回调函数编码的问题,具体在上述代码中指出。。我去百度找了下,暂时是没有找到能直接在页面ajax那边设置编码解决的方式

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,以下是使用jQueryJSON格式数据实现表单的Ajax验证的示例代码: HTML代码: ```html <form id="myForm" action="#" method="post"> <label for="username">用户名:</label> <input type="text" id="username" name="username"><br> <label for="password">密码:</label> <input type="password" id="password" name="password"><br> <input type="submit" value="提交"> </form> ``` jQuery代码: ```javascript $(function() { $('#myForm').submit(function(event) { event.preventDefault(); // 阻止表单的默认提交行为 var formData = $(this).serialize(); // 将表单数据序列化为字符串 $.ajax({ type: 'POST', url: 'validate.php', // 后台处理验证的PHP文件 data: formData, dataType: 'json', // 声明返回的数据类型为JSON success: function(data) { // 请求成功时的回调函数 if (data.status === 'success') { alert('验证通过!'); } else { alert('验证失败:' + data.message); } }, error: function(jqXHR, textStatus, errorThrown) { // 请求失败时的回调函数 alert('请求失败:' + textStatus + ',错误信息:' + errorThrown); } }); }); }); ``` PHP代码: ```php <?php // 模拟验证用户名和密码的函数 function validate($username, $password) { if ($username === 'admin' && $password === '123456') { return true; } else { return false; } } // 获取表单数据 $username = $_POST['username']; $password = $_POST['password']; // 进行验证 if (validate($username, $password)) { $result = array('status' => 'success'); } else { $result = array('status' => 'fail', 'message' => '用户名或密码错误'); } // 返回JSON格式数据 header('Content-Type: application/json'); echo json_encode($result); ?> ``` 以上代码实现了一个简单的表单验证功能,当用户点击提交按钮时,jQuery会将表单数据通过Ajax方式提交给后台PHP文件进行验证。后台PHP文件根据表单数据进行验证,并将验证结果以JSON格式返回给前端页面,前端页面根据返回数据进行相应的处理

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值