Python返回fetch JS函数

2024-04-24 23:32:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个JS调用Python函数。以下是JS电话:

fetch('/ws/invoice/checkDoublon', {
    method  : 'POST',
    headers : {
        'Content-Type': 'application/json'
    },
    body    : JSON.stringify({
        'invoiceNumber' : invoiceNumber.val(),
        'vatNumber'     : vatNumber.val(),
        'id'            : $('#pdfId').val()
    })
}).then(function(response) {
    console.log(response)
});

我的Python代码如下(我使用的是Flask):

^{pr2}$

所有这些都可以,但是console.log(response)根本没有显示我想要从Python“Not duplicate”或“duplicate”中得到的自定义返回。它只表现为响应状态文本因为我返回HTTP代码200

如何检索JS代码上的自定义消息?如果使用的是fetch而不是ajax,那就更好了

提前谢谢


Tags: 函数代码logwsresponsejsvalinvoice
3条回答

您需要从Flask后端返回一个有效的JSON响应

这是因为^{}返回一个^{},您需要调用^{}或{a4}两个返回一个Promise包含数据的Promise,具体取决于您选择的对象

你的js看起来像这样

fetch('/ws/invoice/checkDoublon', {
    method  : 'POST',
    headers : {
        'Content-Type': 'application/json'
    },
    body : JSON.stringify({
        'invoiceNumber' : invoiceNumber.val(),
        'vatNumber'     : vatNumber.val(),
        'id'            : $('#pdfId').val()
    })
  }).then(function(response) {
    response.json().then(function(data) {
      // here data is the object containing your datas
    })
    // or
    response.text().then(function(value) {
      // here value is the string returned by your python script
      let data = JSON.parse(value) // this line transform the string into the same object you get by calling .json() above
    })
});

相关问题 更多 >