我正尝试通过AJAX (jquery)向spring boot服务器发送GET请求。该程序在eclipse内置web浏览器上运行良好,但在chrome/firefox上运行不佳。返回错误{"readyState":0,"status":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>
Spring Boot代码:
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中工作。
发布于 2019-07-28 21:50:41
在您的ajax请求中,您使用了jQuery’s Ajax-Related Methods描述中的dataType:'text'
// 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);
}
https://stackoverflow.com/questions/56204707
复制相似问题