dongren1977
dongren1977
2013-08-07 07:26

ajax php请求Web服务

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.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • douxing8855 douxing8855 8年前

    Since your question is kind of "please do my own homework", my answer points to a good site were you can do your own assignments: http://ajaxpatterns.org/XMLHttpRequest_Call

    What you want to do is to use xmlHTTPRequest() object in a javascript to post data to a webserver and read the response.

    The page linked above has a broken link to a demo, here is the right one: http://ajaxify.com/run/xmlHtttpRequestCall/

    and the source of the page is very interesting, for example please consider this snippet:

    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;
    
    点赞 评论 复制链接分享

为你推荐