[英]want to use JavaScript and Ajax to send to a php script using curl to connect to a remote server
请我想使用JavaScript和Ajax发送到使用Curl发送到远程服务器的php脚本。 但是第一次我将发送到该php脚本时,我会得到结果,第一次后我将不再得到结果,只是我刷新页面。 我想这样做而不刷新页面。 也就是说,我想发送到远程服务器很多次并得到结果。
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()函数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.