简体   繁体   English

在后端通过AJAX无法通过POST获取变量,而在前端完全可以

[英]Can't get variable by POST at backend via AJAX, while it's perfectly fine at front-end

Ok, so, here is my problem. 好的,这是我的问题。 I'm trying to send tag attribute which I store in javascript variable to backend(PHP) via AJAX. 我试图通过AJAX送我存储在JavaScript变量后端(PHP)标签属性。

$.ajax({
    type: "POST",
    url: '/requests/mercury.php',
    data: {url : $(this).data('link')},
    success: function(data){
       console.log(data);
    }

It's a URL which I want to pass to CURL request. 这是我要传递给CURL请求的URL。

CURL request is working if I write correct URL manually, but by some reason I can't retrieve variable at backend. 如果我手动编写正确的URL,则CURL请求有效,但是由于某种原因,我无法在后端检索变量。 I've tried debugging and it seems like I'm getting an empty array and I don't know why. 我试过调试,似乎正在获取一个空数组,但我不知道为什么。

$link = $_POST['url'];

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://mercury.postlight.com/parser?url=".$link);

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    "x-api-key: AU5zjyEqyL0LgR8zkb4Iurhlenpn52bGtbiqJA4t",
));

$x = curl_exec($ch);

curl_close($ch);

Tried to deploy at localhost(MAMP) and Heroku, at both places same problem. 试图部署在本地主机(MAMP)和Heroku,这两个地方都存在相同的问题。

Full code is avalible at https://github.com/pjotrleshkin/RSSParsing 完整的代码avalible在https://github.com/pjotrleshkin/RSSParsing

Hi Pjotr Leškin there was an issue on HTTP request Methods. 嗨,Pjotr​​Leškin,关于HTTP请求方法的问题。 On your index.php the Ajax code is working fine because you are sending POST request but on link click you are opening /requests/mercury.php that is a GET request. 在index.php上,Ajax代码工作正常,因为您正在发送POST请求,但是在链接单击时,您正在打开/requests/mercury.php这是一个GET请求。 So, to get the parameter on load of /requests/mercury.php you need $_GET['url'] and need to pass query string along with url. 因此,要在/requests/mercury.php加载时获取参数,您需要$ _GET ['url']并需要将查询字符串与url一起传递。 I have made little change on your code to handle both GET and POST request. 对于处理GET和POST请求的代码,我所做的更改很少。

echo "<a href='requests/mercury.php' data-link = ".$item->link." target='_blank'>";

to

echo "<a href='requests/mercury.php?url={$item->link}' data-link = ".$item->link." target='_blank'>";

and

$link = $_POST['url'];

to

$link = "";

if (isset($_POST['title'])) {
    $link = $_POST['url'];
} else  {
    $link = $_GET['url'];
}

And I have created a pull request on your github code. 我已经在您的github代码上创建了pull请求。 Hope this will help you. 希望这会帮助你。

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

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