如何使用JavaScript访问本地hug API?

2024-05-13 01:16:11 发布

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

我有一个apache2web服务器和一个Python服务器在运行。两者都在不同的端口上运行。我现在想使用jQuery向hug服务器发送一个请求。因为这是跨域的,所以我想我必须使用类似的东西:How do I send an AJAX request on a different port with jQuery? 带有回调参数的jsonp。你知道吗

我的问题是: -我的方法合理吗? -hug支持带回调的jsonp吗? -javascript和pythonapi之间有没有更好的通信解决方案?你知道吗


Tags: 端口服务器ansendonrequestajaxjquery
1条回答
网友
1楼 · 发布于 2024-05-13 01:16:11

如果只需要在API上发送GET请求,可以使用jQuery方法:

$.getJSON(your_url, function(json_received){
      console.log(json_received);
    });

如果需要通过POST请求发送数据,则需要在ajax方法中添加更多参数:

    $.ajax({
          type: 'POST',
          contentType: 'application/json; charset=utf-8',
          url: your_url,
          dataType: 'json',
          data: JSON.stringify({'message':'your_message}),           
          success: function(data_received) {
            console.log(data_received);
          },
          error: function(error) {
            console.log(error);
          }
      });

在API响应中,您需要添加参数{'Access-Control-Allow-Origin': '*'},以允许跨域。你知道吗

相关问题 更多 >