1

我正在使用 php curl 使用 Ajax 从我的 javascript 发出 http get long 轮询请求。这是来自 javascript 的调用

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

这是我在 myport.php 文件中进行 php 调用的方法

 <?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

如果我直接从 js 拨打电话,我会这样做

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

我是 php 和 curl 的新手,我想知道如何传递该变量的值,以便获取调用的参数。

4

2 回答 2

0

如果我理解正确,并且您只想将变量的值附加$i到 cURL 调用中,您可以这样做:

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

甚至,

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

另请注意,$函数调用之前没有:它curl_setopt()不是$curl_setopt()$用于变量,如$ch)。

编辑

澄清问题后,您似乎需要将此i变量从 JavaScript 获取到 PHP。GET您可以在 AJAX 调用中将其作为参数传递:

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

然后,从 PHP 中,您可以像这样使用它:

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

您还应该验证是否$_GET['index']实际传入:

if (!isset($_GET['index']))
{
    die("The index was not specified!");
}
于 2015-07-10T23:10:17.507 回答
0

您可以i像在上一个示例中一样从 JavaScript传递?index=,然后从全局变量中读取indexphp 中的值$_GET["index"]

于 2015-07-10T23:17:29.587 回答