简体   繁体   English

想要使用JavaScript和Ajax使用curl将其发送到php脚本以连接到远程服务器

[英]want to use JavaScript and Ajax to send to a php script using curl to connect to a remote server

Please i want to use JavaScript and Ajax to send to a php script that sends to a remote server using Curl. 请我想使用JavaScript和Ajax发送到使用Curl发送到远程服务器的php脚本。 But the first time i will send to this php script, i will get a result, after the first time i will no longer get a result, except i refresh the page. 但是第一次我将发送到该php脚本时,我会得到结果,第一次后我将不再得到结果,只是我刷新页面。 I want to do this without refreshing the page. 我想这样做而不刷新页面。 that is, i want to send to the remote server so many times and get a result. 也就是说,我想发送到远程服务器很多次并得到结果。

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);
}

my php script 我的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";
  }
?>

As long as you are able to send requests you could get response from the php script. 只要您能够发送请求,就可以从php脚本获得响应。

Check you are sending requests from the browser net panel using firebug 使用Firebug检查您是否正在从浏览器网络面板发送请求

In js code see calling go() function by logging some help text to console panel using console.log('calling go function') 在js代码中,请使用console.log('calling go function')将一些帮助文本记录到控制台面板中,以调用go()函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM