douwen7603 2015-07-10 23:01
浏览 105
已采纳

通过AJAX将动态参数从JavaScript传递到PHP,以便在cURL调用中使用

I am using php curl to make a http get long polling request from my javascript using Ajax. Here is the call from javascript

var i;
i++;
$.ajax({
   url:"http://localhost/myport.php",
   type: GET,
   success: function(response){ ...},
   ...
   ...

Here is how I make the php call in the myport.php file

 <?php
 $ch=curl_init();
 $curl_setopt($ch, CURLOPT_URL, "http://localhost:7555/test?index=" //Here I need to set a value (the variable i) in the above JS

If I making the call directly from js, I would do

$.ajax({ url:"http://localhost:7555/test?index=" + i

I am new to php and curl, I am wondering how I can pass the value of that variable so I can get a parameter for the call.

  • 写回答

2条回答 默认 最新

  • dongtui0650 2015-07-10 23:10
    关注

    If I understand correctly, and you just want to append the value of the variable $i to the cURL call, you'd do this:

    <?php
    $ch=curl_init();
    curl_setopt($ch, CURLOPT_URL, "http://localhost:7555/test?index=" . $i);
    

    Or even,

    curl_setopt($ch, CURLOPT_URL, sprintf("http://localhost:7555/test?index=%d", $i));
    

    Also note hat there is no $ before a function call: it's curl_setopt() not $curl_setopt() ($ is for variables, like $ch).

    Edit

    Upon clarification of the question, it seems you need to get this i variable from JavaScript to PHP. You can pass it as a GET parameter in your AJAX call:

    var i;
    i++;
    $.ajax({
       url:"http://localhost/myport.php?index=" + i,
       type: GET,
       success: function(response){ ...},
       ...
       ...
    

    Then, from PHP, you can use it like this:

    curl_setopt($ch, CURLOPT_URL, sprintf("http://localhost:7555/test?index=%d", $_GET['index']));
    

    You should also verify that $_GET['index'] was actually passed in:

    if (!isset($_GET['index']))
    {
        die("The index was not specified!");
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误