-1

I need to write a php code using ajax to get a respond from http://www.w3schools.com/webservices/tempconvert.asmx/FahrenheitToCelsius webserver. below is the code which will post request and get the respond. since it is a post request the site get refreshed. without refreshing i need the respond.I dont know how to do it in ajax. please help me. thanks alot.

    <?php
    if (isset($_POST['Fahrenheit'])&&$_POST['Fahrenheit']!=null) {
    $out = print_name($_POST['Fahrenheit']);
    }
    else {
     print_form();
    }

    function print_name($name) {
        $ch = curl_init();
        $far = 'Fahrenheit='.$name;
        curl_setopt($ch, CURLOPT_URL,"http://www.w3schools.com/webservices/tempconvert.asmx     /FahrenheitToCelsius");
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$far);

        // http_build_query(array('postvar1' => 'value1')));

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $server_output = curl_exec ($ch);
        curl_close ($ch);
        echo 'It is: '.$server_output;
        return $server_output;
    }


    function print_form() {
      echo '
        <form method="post">
    <table>
      <tr>
        <td>Fahrenheit to Celsius:</td>
        <td>
        <input class="frmInput" type="text" size="30" name="Fahrenheit">
        </td>
      </tr>
      <tr>
        <td></td>
        <td align="right">
         <input name="cel" type="submit" value="Submit" class="button">
         </td>
      </tr>
    </form>
      ';
    }

please help me.

4

1 回答 1

0

由于您的问题有点像“请自己做作业”,因此我的回答指向一个很好的网站,您可以自己做作业:http ://ajaxpatterns.org/XMLHttpRequest_Call

您要做的是在 javascript 中使用 xmlHTTPRequest() 对象将数据发布到网络服务器并读取响应。

上面链接的页面有一个损坏的演示链接,这里是正确的:http ://ajaxify.com/run/xmlHtttpRequestCall/

并且页面的来源非常有趣,例如请考虑这个片段:

function createXMLHttpRequest() {
  try { return new XMLHttpRequest(); } catch(e) {}
  alert("XMLHttpRequest not supported");
  return null;
}
var xhReq = createXMLHttpRequest();
    xhReq.open("GET", "sumGet.php?figure1=5&figure2=1", false); //here method of sending data and server page where to send to
    xhReq.send(null);
    var serverResponse = xhReq.responseText;
    $("response").innerHTML = serverResponse;
于 2013-08-09T20:41:50.957 回答