【问题标题】:Simple ajax GET request not working on my Django webpage简单的 ajax GET 请求在我的 Django 网页上不起作用
【发布时间】:2016-04-24 09:37:06
【问题描述】:

我对 Django 和 Ajax 都很陌生(这是我第一次同时使用这两种方法),并且我的代码收到错误消息。基本上我有一个 HTML 按钮,在由 Django 中的模板生成的网页上,它应该调用一个使用 jquery 分配的函数 onclick。单击时,该按钮应向具有指定 URL 的网页发送 GET 请求。这就是我想要它做的所有事情,但是,它似乎不起作用。它不断抛出错误。以下是部分代码:

<button class="btn btn-primary toChange">Click me</button>

    $(".toChange").click(function(){
        $.ajax({
            url: 'localhost:8000/MyApp/ajax_test',
            type: 'GET', 
            success: function(data) {
                alert(data);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log(JSON.stringify(jqXHR));
                console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
            }
        }); 
      //alert("Something happened!")
    });


</script>

我对我想要得到的东西的看法是:

def test(request):
    return HttpResponse("Congrats, you've got it!")

目前,我正在使用 Firefox 查看 localhost:8000 上的网页。如果我在单击按钮时查看控制台,这就是我所看到的。

{"readyState":0,"status":0,"statusText":"[Exception... \"<no message>\"   nsresult: \"0x805e0006 (<unknown>)\"  location: \"JS frame :: https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js :: .send :: line 5\"  data: no]"}

AJAX error: error : [Exception... "<no message>"  nsresult: "0x805e0006 (<unknown>)"  location: "JS frame :: https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js :: .send :: line 5"  data: no]

我尝试研究这些错误,但我不确定,但这可能是 Firefox 不允许请求通过的错误。有人可以帮帮我吗?

【问题讨论】:

  • 而不是url: 'localhost:8000/MyApp/ajax_test',;你能试试url: '//localhost:8000/MyApp/ajax_test',
  • 哦,哇,这个和另一个答案都有效。如果可以的话,你能解释一下出了什么问题吗?非常感谢!

标签: javascript jquery html ajax django


【解决方案1】:

更改您的网址:

$(".toChange").click(function(){
    $.ajax({
        url: 'localhost:8000/MyApp/ajax_test', # change here

$(".toChange").click(function(){
    $.ajax({
        url: '/MyApp/ajax_test',

【讨论】:

  • 这成功了!太感谢了!我之前的有什么问题,是在url中放入了不必要的数据吗?
  • 如果您通过单击答案旁边的勾号来接受此答案,那就太好了,这样其他用户将来可能会发现它有用。 :)
  • 哦,对不起,你走了
  • 实际上您提供的网址实际上不是有效的网址。您需要使用//localhost:8000/...http://localhost:8000/... 或简单地使用/MyApp/...
猜你喜欢
  • 2018-03-06
  • 1970-01-01
  • 2020-07-11
  • 2014-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-03
相关资源
最近更新 更多