2016-11-19 67 views
-2

我试图使用使用Chrome控制台下面发送一个Ajax请求到服务器:JQuery Ajax语法错误?

$.ajax({ 
    url: 'http://www.adidas.co.uk/on/demandware.store/Sites-adidas-GB-Site/en_GB/Cart-MiniAddProduct', 
    data: { 
     "request": "ajax", 
     "Quantity": "1", 
     "g-recaptcha-response": "redacted", 
     "responseformat": "json", 
     "sku": "AQ5934", 
     "pid": "AQ5934_660" 
    }, 
    method: 'POST', 
    crossDomain: true, 
    contentType: 'application/x-www-form-urlencoded', 
    xhrFields: { 
     withCredentials: true 
    }, 
    complete: function(data, status, xhr) { 
     console.log(status); 
     console.log(data); 
    } 
}); 

然而,我发现了以下错误:

Uncaught TypeError: $.ajax is not a function 
    at <anonymous>:1:3 

我导致相信这个问题是由于语法错误,我找不到在下面的方法中的语法错误,有人可以帮我找到它吗?

+1

你是如何加载jQuery脚本? – winseybash

+0

不应该因为我使用的是Chrome控制台 –

+0

jQuery是否在您使用控制台检查的页面上加载? – winseybash

回答

1

发生此错误的原因是您的项目可能没有jQuery库。

你总是需要你的JavaScript文件之前添加库正常工作,就像这样:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
<script src="/your/file.js"></script> 
+0

不应该因为我使用铬控制台 –

+1

你总是需要添加jquery库,带或不带chrome控制台。 –

+0

我的歉意,我不知道这一点。感谢您的帮助 –

0

首先,确保你加载jQuery库,您可以通过使用(版本下面可以做改变):

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 

其次,从你提供的,你是不是把你的Ajax调用jQuery的文件准备函数内部的代码的外观。执行以下操作(第一和最后一行是新的):

$(document).ready(function(){ /* NEW LINE */ 
    $.ajax({ 
     url: 'http://www.adidas.co.uk/on/demandware.store/Sites-adidas-GB-Site/en_GB/Cart-MiniAddProduct', 
     data: { 
      "request": "ajax", 
      "Quantity": "1", 
      "g-recaptcha-response": "redacted", 
      "responseformat": "json", 
      "sku": "AQ5934", 
      "pid": "AQ5934_660" 
     }, 
     method: 'POST', 
     crossDomain: true, 
     contentType: 'application/x-www-form-urlencoded', 
     xhrFields: { 
      withCredentials: true 
     }, 
     complete: function(data, status, xhr) { 
      console.log(status); 
      console.log(data); 
     } 
    }); 
}); /* NEW LINE */ 

如果你在本地主机上测试这一点,那么你会得到一个错误CORS。

XMLHttpRequest cannot load http://www.adidas.co.uk/on/demandware.store/Sites-adidas-GB-Site/en_GB/Cart-MiniAddProduct. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. 

也许你有一个单独的脚本进行身份验证?