想要使用JavaScript和Ajax发送到php脚本,使用curl连接到远程服务器吗
请我想使用JavaScript和Ajax发送到php脚本,该脚本使用Curl发送到远程服务器。但是第一次发送到这个php脚本时,我会得到一个结果,在第一次之后,我将不再得到结果,除非我刷新页面。我想在不刷新页面的情况下执行此操作。也就是说,我想多次发送到远程服务器并得到结果想要使用JavaScript和Ajax发送到php脚本,使用curl连接到远程服务器吗,javascript,php,curl,Javascript,Php,Curl,请我想使用JavaScript和Ajax发送到php脚本,该脚本使用Curl发送到远程服务器。但是第一次发送到这个php脚本时,我会得到一个结果,在第一次之后,我将不再得到结果,除非我刷新页面。我想在不刷新页面的情况下执行此操作。也就是说,我想多次发送到远程服务器并得到结果 function go() { var xmlhttp = new XMLHttpRequest(); var url = "url.php"; var text = document.getElem
function go() {
var xmlhttp = new XMLHttpRequest();
var url = "url.php";
var text = document.getElementById("text").value;
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var variables = "text="+text+"&name="+name+"&email="+email;
xmlhttp.open("POST", url, true);variables in the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var data = xmlhttp.responseText;
document.getElementById("flash-message").innerHTML = data;
}
}
xmlhttp.send(variables);
}
我的php脚本
<?php
if(!empty($_POST['text']) && !empty($_POST['name']) && !empty($_POST['email']) {
$url = "http://url.com/api";
$xmlString = "
<profile>
<names>
<firstname>john</firstname>
<lastname>doe</lastname>
</names>
</profile>";
$fields = "XML=" . urlencode($xmlString);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
echo $response = curl_exec($ch);
curl_close($ch);
}else {
echo "Please fill in those fields";
}
?>
只要您能够发送请求,就可以从php脚本获得响应
检查是否使用firebug从浏览器网络面板发送请求
在js代码中,使用console.log('calling go function')将一些帮助文本记录到控制台面板,以查看调用go()函数。我第一次发送到脚本时得到响应,但之后,我没有得到响应。除非我刷新页面。你必须发送一个新的请求才能得到响应,这就是为什么你第一次得到响应的原因。例如,当你点击一个按钮时,尝试调用函数go(),这样你将发送一个新的请求并且肯定会得到响应