javascript - 向本地主机发送请求时,jQuery xhr.status 返回 0

标签 javascript java jquery json rest

更新 - 2016-01-30

正如我在评论中所建议的:

  1. 已安装 XAMPP
  2. 将我的页面放在 Apache 上并运行服务器
  3. 确保页面和脚本正在执行(简单警报测试)
  4. 将 xhrFields: withCredentials 设置为 false,以按照唯一答案中的建议和教导提出 CORS 请求 here

我仍然无法通过该请求。这是控制台日志:

XMLHttpRequest cannot load http://localhost:8080/RimmaNew/rest/appointments. 
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 400

这里是“用户端”的外观(如果这有任何帮助的话): enter image description here

------------------初始票------------------------------------ --

我有一个在本地运行的 Java Rest 应用程序,到目前为止接受一个 get 方法并返回一个 json 字符串: Successful get by id call

另一种方法是 POST,它应该转换、验证并保存发送表单中的信息并返回 200 答案。如果在转换、验证或持久化过程中出现任何问题,则会抛出异常(例如 BadRequest 或 500)。

这是剩下的方法(为了简洁起见,我省略了验证、构建方法以及转换器和转换器提供程序类):

@POST
@Produces("application/json")
@Consumes("application/x-www-form-urlencoded")
public Response bookAppointment(@FormParam("date") Date appDate,
        @FormParam("time") Time appTime, @FormParam("type") String appType,
        @FormParam("clientName") String clientName, @FormParam("email") String clientEmail,
        @DefaultValue("") @FormParam("message") String clientMsg) {
    //externalize the validation of all fields to concentrate on "positive"
    //scenario only
    validator(appDate, appTime, appType, clientName, clientEmail);
    Appointment appointment = build(appDate, appTime, appType,clientName, 
                clientEmail, clientMsg);
    try {
        repository.add(appointment);
        return Response.ok(appointment).build();
    } catch (Exception e) {
        throw new InternalServerErrorException("Something happened in the application "
                + "and this apointment could not get saved. Please contact us "
                + "to inform us of this issue.");
    }
}

客户端不在应用程序内(我认为这可能会有用) - 它是我计算机上的一个简单的 HTML 文件,其中包含以下 jQuery 脚本:

<script type='text/javascript'>
    $(document).ready(function(){
         $('form#appointmentForm').submit(function(ev){
             ev.preventDefault();
            $.ajax({
                url: 'localhost:8080/RimmaNew/rest/appointments',
                type: 'post',
                dataType: 'json',
                data: $('form#appointmentForm').serialize(),
                contentType: 'application/x-www-form-urlencoded',
                beforeSend: function() {                        
                    $('#ajaxResponse').html("<img src='245.gif' />");                        
                },
                success: function(data) {
                    $('#ajaxResponse').html("<span style='color:white; background-color: green;' class='glyphicon glyphicon-ok'></span><p>"+JSON.stringify(data)+"</p>")
                    .fadeIn("slow");
                },
                error:  function(xhr, ajaxOptions, thrownError){
                    $('#ajaxResponse').html("<span style='color:white; background-color: red;' class='glyphicon glyphicon-exclamation-sign'></span><p>Status: ").append(xhr.status)
                    .append("</p>").fadeIn("slow");
                }
            });               
        });            
    });
</script>

我想提交一个表单,以便使用 @FormParam 带注释的属性访问其参数。对于我发送的每个请求,我都没有收到任何抛出的错误,并且状态始终为 0。您是否看到我在哪里出错或缺少什么?

enter image description here

最佳答案

状态代码 0 表示请求未发生。为了获得状态代码,必须发生有效的 http 交互,如果没有发生,则没有状态代码。

发生这种情况的主要原因是:

  1. 无法解析 DNS
  2. 无法建立与主机/端口的连接
  3. CORS 问题,HTML 不是由与服务器相同的主机/端口提供服务。在这种情况下,您需要编写 CORS 策略以允许特定域 向服务器发出ajax请求。
  4. HTML 是本地文件,这是 CORS 问题的特殊情况,某些浏览器不允许在没有主机的情况下进行连接。

所有这些都应该在 javascript 控制台上显示错误(最奇怪的是 CORS,它显示为失败的 OPTIONS 请求)

关于javascript - 向本地主机发送请求时,jQuery xhr.status 返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35050996/

相关文章:

javascript - 为什么 JSLint 限制使用 HTML 事件处理程序?

java - 如何初始化 NamedParameterJdbcTemplate 变量

java - org.hibernate.hql.ast.QuerySyntaxException 表未映射

java - 从 swing jCombobox 迁移到 javaFX ComboBox

jquery - 不带数据的 AJAX GET 请求的响应处理

javascript - CasperJS支持 session 机制吗?

javascript - 从 JSON Store 的子集创建 Store

javascript - 如何使用 amcharts 创建多环 donut 饼图?

jquery - 如何在 .NET 应用程序中引用 jQuery 的绝对路径

asp.net-mvc - 如何使用 MVC 和 jQuery AJAX 传递对象?