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 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器