我正在尝试通过Ajax(JQuery(将Get请求发送到Spring Boot服务器。该程序在Eclipse Innoult Web浏览器上工作正常,但在Chrome/Firefox中不行。它给出错误{" readystate":0,"状态":0," statustext":" error"}。
html页面:
<html>
<head>
<script src="jquery-3.4.1.min.js"></script>
<script>
var q = 0;
$(function () {
$("input[name='type']").click(function () {
q = $("[name='type']:checked").val();
});
$("#btn").click(function () {
t = $("#in").val();
$.ajax({
type: "get",
dataType: "text",
url: "http://localhost:9001/doubleit?data=" + t + "&type=" + q,
success: function (data) {
alert(data);
},
error: function (e) {
alert('we have trouble ' + JSON.stringify(e));
}
});
});
});
</script>
</head>
<body>
<input type="text" id="in"/>
double it<input type="radio" name="type" value="2"/>
triple it<input type="radio" name="type" value="3"/>
<br/><br/>
<input type="button" value="submit" id="btn"/>
</body>
</html>
春季引导代码:
package jqrywithjava;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DoubleitController {
@GetMapping("/doubleit")
public int nobodyCares(@RequestParam("data") int pqr, @RequestParam("type") int xyz) {
System.out.println("Hello");
return pqr * xyz;
}
}
和
package jqrywithjava;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
请帮助我在Chrome或Firefox中进行此工作。
在您使用dataType:'text'
的Ajax请求中,来自JQuery的AJAX相关方法描述
// The type of data we expect back
dataType : "text",
将您的ajax更新为
$.ajax({
type: "get",
url: "http://localhost:9001/doubleit?data=" + t + "&type=" + q,
success: function (data) {
alert(data);
},
error: function (e) {
alert('we have trouble ' + JSON.stringify(e));
}
});
然后将@ResponseBody
添加到控制器方法中,然后将结果返回为字符串。
@GetMapping("/doubleit")
@ResponseBody
public String nobodyCares(@RequestParam("data") int pqr, @RequestParam("type") int xyz) {
System.out.println("Hello");
Integer result = pqr * xyz;
return Integer.toString(result);
}