dpv21589 2018-02-04 12:53
浏览 156
已采纳

在传递变量时从Jquery AJAX执行cURL请求

I've researched a lot about PHP cURL and already know a fair amount of Jquery Ajax however what i'm trying to do isn't straight down the line. I'm making an API call using an API Login button that returns a users nickname.

I then make an ajax request to a php file containing the curl paramaters within which i want to pass the users nickname.

RESOLVED

Using data in the AJAX Request i was able to successfully send the javascript variable nickname as a parameter.

The variable was then accessible via $nickname = $_GET['nickname']; in the cURL PHP file.

Thank you to rollstuhlfahrer for providing the solution marked below.


Ajax Request:

var nickname = API.getUserInfo().value.nickname;
$.ajax({
  method: 'GET',
  url: "/curl-php-file.php",
  cache: false,
  data: {
    nickname: nickname, // Sends data as a URL paramater
  }
  success: function(response) {
    // Data
    var data = response.data.data;
    console.log(data);
  },
  error: function(response, val) {
    console.log("AJAX Request Failed");
  }
});

cURL PHP File:

$nickname = $_GET['nickname']; // Gets data from AJAX
require_once("../../../../../wp-load.php");
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://.../?nickname=' . $nickname,
CURLOPT_HTTPHEADER => array(
  'Accept: application/json',
  'Authorization: MYTOKEN'
)
));
$resp   = curl_exec($curl);
wp_send_json_success(json_decode($resp));
curl_close($curl);
exit;
  • 写回答

1条回答

  • douzhang8144 2018-02-04 13:17
    关注

    Since you are using GET, you can just pass it along as a query parameter:

    $.ajax({
      method: 'GET',
      url: "/curl-php-file.php?nickname=" + nickname,
      cache: false,
      success: function(response) {
        // Data
        var data = response.data.data;
        console.log(data);
      },
    }
    

    Another option. This has the beauty if built-in character encoding:

    $.ajax({
      url: "/curl-php-file.php",
      method: "get", 
      data: { 
        nickname: nickname,
      },
    

    Source

    Then in your PHP code, you retrieve the passed parameter:

    $nickname = $_GET['nickname'];
    

    And append it to your URL:

    CURLOPT_URL => 'https://.../?nickname=' . $nickname,
    

    You should do some checking, if the nickname is a valid one before sending it off via curl.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)