2013-08-07 172 views
-1

我需要用ajax寫一個php代碼來獲得http://www.w3schools.com/webservices/tempconvert.asmx/FahrenheitToCelsius網絡服務器的響應。下面是將發佈請求並獲得回覆的代碼。因爲這是一個帖子請求網站刷新。無需刷新我需要回應。我不知道如何在ajax中做到這一點。請幫幫我。非常感謝。ajax php請求到網絡服務

<?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> 
     '; 
    } 

請幫幫我。

+0

以這種方式工作,你需要重新加載頁面以獲取帖子的值,你可以通過刪除條件來打印表單以顯示它,或者你可以將PHP文件的一部分放到另一個文件並使用ajax – 2013-08-07 07:35:30

+0

@Akam ok但是我不知道阿賈克斯。你能幫我做到嗎?我不知道如何傳遞值以及如何獲得響應並查看這些文件。感謝您的支持 –

+0

您顯然不滿足對被問問題有最少理解的要求。嘗試研究和學習AJAX,因爲SO並非真正意圖回答像「教我AJAX」這樣的請求。 –

回答

0

因爲你的問題是怎麼樣的「請做我自己的功課」,我的回答指向一個好的網站是你可以做自己的作業:http://ajaxpatterns.org/XMLHttpRequest_Call

你想要做的是使用XMLHttpRequest()對象在JavaScript中發佈數據到網絡服務器並閱讀響應。

以上鍊接的頁面有一個破碎的鏈接到一個演示,這裏是正確的: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;