简体   繁体   English

相当于Python request.post()的jQuery

[英]Jquery equivalent of Python requests.post()

So i was trying to work with HackerEarth Api and wanted to incorporate the compile/run feature on my website. 因此,我试图与HackerEarth Api合作,并希望将编译/运行功能纳入我的网站。 According to the documentation that can be found here - https://www.hackerearth.com/docs/wiki/developers/v3/ i got to know that using the following python script i can get a json response for my code . 根据可以在这里找到的文档-https: //www.hackerearth.com/docs/wiki/developers/v3/我知道,使用以下python脚本,我可以为我的代码获取json响应。

   #! -*- coding: utf-8 -*-

import requests

# constants
RUN_URL = u'https://api.hackerearth.com/v3/code/run/'
CLIENT_SECRET = '5db3f1c12c59caa1002d1cb5757e72c96d969a1a'
#not my own secret key

source = "print 'Hello World'"

data = {
    'client_secret': CLIENT_SECRET,
    'async': 0,
    'source': source,
    'lang': "PYTHON",
    'time_limit': 5,
    'memory_limit': 262144,
}

r = requests.post(RUN_URL, data=data)
print r.json()

I tried running the above code and it works fine. 我尝试运行上面的代码,它工作正常。 My site is built using plain html,cc,js,jquery,bootstrap and i was trying to get this working using jquery post method . 我的网站是使用纯HTML,cc,js,jquery,bootstrap构建的,而我正尝试使用jquery post方法使此工作正常。

What i tried was - 我试过的是-

code=document.getElementById('codeinput').value;
langaugeUsed=document.getElementById('languageSelector').value;
url='https://api.hackerearth.com/v3/code/compile/';
secret = '5db3f1c12c59caa1002d1cb5757e72c96d969a1a';    //not my own secret key


$.post(url, {client_secret: secret,
async: 0,
source: code,
lang: languageUsed,
dataType:'json',
time_limit: 5,
memory_limit: 262144 },
     function(returnedData){
        alert(returnedData);
}, 'json');

When i checked my console i had these errors after trying to run the script - 当我检查控制台时,尝试运行脚本后出现了以下错误-

Failed to load resource: the server responded with a status of 403 (Forbidden) index.html#:1 XMLHttpRequest cannot load https://api.hackerearth.com/v3/code/compile/ . 无法加载资源:服务器的状态为403(禁止访问)index.html#:1 XMLHttpRequest无法加载https://api.hackerearth.com/v3/code/compile/ No 'Access-Control-Allow-Origin' header is present on the requested resource. 所请求的资源上没有“ Access-Control-Allow-Origin”标头。 Origin 'null' is therefore not allowed access. 因此,不允许访问原始“空”。 The response had HTTP status code 403. 响应的HTTP状态码为403。

Can anyone help me with this issue? 谁能帮我解决这个问题?

You are facing the issue due to CORS . 由于CORS,您正面临这个问题。 By Default, Browser don't allow to send the request on different urls. 默认情况下,浏览器不允许使用不同的URL发送请求。 So you need to manually allow this by adding the CORS header. 因此,您需要通过添加CORS标头来手动允许此操作。

You can take a good look at CORS Python Library 您可以看一下CORS Python库

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM