我正在使用 php curl 使用 Ajax 从我的 javascript 发出 http get 长轮询请求。这是来自 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 的新手,我想知道如何传递该变量的值,以便获取调用的参数。
最佳答案
如果我理解正确,并且您只想将变量 $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。您可以将其作为 AJAX 调用中的 GET
参数传递:
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!");
}
关于javascript - 通过 AJAX 将动态参数从 JavaScript 传递到 PHP 以在 cURL 调用中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31351573/