jquery ajax "readyState":0,"status":0,"statusText":"error"

时间:2019-05-19 04:15:10

标签: jquery ajax spring-boot

I am trying to send a GET request through AJAX (jquery) to a spring boot server. The program is working fine on eclipse inbuilt web browser but not in chrome/firefox. It gives error {"readyState":0,"status":0,"statusText":"error"}.

HTML page:

<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 Code:

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;
    }

}

and

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);
    }
}

Please help me make this work in chrome or firefox.

1 个答案:

答案 0 :(得分:0)

在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添加到控制器方法,并从那里以String形式返回结果。

@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);
}