【问题标题】:after ajax call , the code after waiting for Json response could not be executedajax调用后,等待Json响应后的代码无法执行
【发布时间】:2021-06-05 14:04:52
【问题描述】:

我使用 Django2 开发了一个网络应用程序。 我在前端,在 ajax 调用之后,chrome dev 上的网络选项卡确实显示了 200 状态代码,但我没有看到任何警报框。我的应用卡在这条线上等待 json: const msg_json = await response.json(); ,以下警报不会执行

async function myFunction() {
  Swal.fire({
    title: '',
    text: "Do you want to confirm entries?",
    type: 'warning',
    showCancelButton: true,
    confirmButtonColor: '#3085d6',
    cancelButtonColor: '#d33',
    confirmButtonText: 'Yes',
    cancelButtonText: 'No'
  }).then(
    async(result) => {
      if (result.value) {
        $.ajax({
          url: '/content_checklist_name_url/',
          type: 'POST',
          data: $(this).serialize(),
          cache: false,
          success: function(data) {
            var comment_html = "<div id='myform_1'>" + data['log_info'] + "</div>";
            $('#myform_1').remove();
            $('#ajax_data').prepend(comment_html);
            $('#myform_input').val('');
          },

        });
        const response = await fetch({ % url 'bms:content_checklist_name_url' %
        });
        const msg_json = await response.json();

        alert(msg_json.responseText)
        let a = msg_json;
        if (a === "Duplicate Entry. This Course Code already exists.") {
          Swal.fire({
            title: '',
            text: 'Duplicate Entry. This Course Code already exists.',
            type: 'error',
          })


        } else {
          Swal.fire({
            title: '',
            text: 'Entries have been saved.',
            type: 'success',
          })


        }
        // },
        // failure: function(data)
        // {
        //  alert('Got an error dude');
        //  }
        // });
      } else {
        window.stop();
      }
    }
  )
}
<form id="myform" action="/content_checklist_name_url/" method="POST">
  ...
</form>
<button class="button" onclick="myFunction()" type="button" id="submit">SUBMIT</button>

后端视图.py:

    @csrf_exempt
def content_checklist_name_url(request):

  if request.method == 'POST':    
    
         ...
    msg = "success"   

    obj = {"msg": msg}

    context = {'msg_json': json.dumps(obj)}
    return render(request, 'bms/main.html',context=context)

我在控制台中收到错误:VM355:4 Uncaught (in promise) SyntaxError: Unexpected token &lt; in JSON at position 3

不显示警告框。

我如何检查哪里出了问题?

【问题讨论】:

  • myFunction() 在哪里以及如何被调用? ajax 应该在表单提交处理程序中。你打电话.submit() 然后调用ajax。这个顺序没有意义
  • 你应该转储 jQuery 的 $.ajax 并改用原生的 fetchconst response = await fetch(url); const msg_json = await response.json(); 工作完成
  • @JeremyThille 更新了我的问题,使用你的方法产生了新问题
  • 呃?你没有使用我的方法。您仍在同时使用$.ajaxawait fetch

标签: javascript django ajax


【解决方案1】:

您的视图正在等待一个 POST 并且您正在发送一个 GET,因此该分支不会被执行。另外,通过html提交表单,让浏览器换页,这样表单提交就不会调用ajax了。

【讨论】:

  • 那怎么解决呢?
  • 使用 ajaxForm 并通过 POST 发送
  • 用了你的方法,收不到回复,我已经更新了代码,请看我更新的问题
  • 我认为问题出在 $(this).serialise 因为这不是表单,请检查浏览器通过控制台中的网络选项卡发送给 Django 的内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-26
  • 1970-01-01
  • 2013-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多