2011-08-04 43 views
0

我嘗試使用XMLHttpRequest()將數據發佈到url。 我寫了下面的javascript:在參數列表後傳遞php變量爲javascript函數錯誤:缺失)

function makePostRequest(url, params) { 
var httpRequest = new XMLHttpRequest(); 
httpRequest.open("POST", url, true); 
//Send the proper header information along with the request 
httpRequest.setRequestHeader("Content-type", "application/json"); 

httpRequest.onreadystatechange = function() {//Call a function when the state changes. 
    if(httpRequest.readyState == 4 && httpRequest.status == 200) { 
     alert(httpRequest.responseText); 
    } 
} 
httpRequest.send(params);} 

然後我需要將兩個PHP變量傳遞到PHP文件這個功能,一個是URL,另一個是被張貼JSON數據。

$url = "http://www.hello.com"; 
$json_str = "{\"format\": \"json\", 
      \"event\": \"revert\", 
     \"api_key\": \"$wgAPIKey\"}"; 

$editpage->editFormTextTop = 
      "<input type='button'value='hello' onclick='makePostRequest(\"$url\", \"$json_str\")' />"; 

執行後,我得到了來自螢火蟲以下錯誤:

missing) after argument list 
+0

沒有告訴你的行號?參數列表後面的「 – Ibu

+1

」缺失)看起來像是一個JavaScript錯誤,請嘗試找出(使用Firebug或類似的工具)確切地說這個錯誤被觸發的位置;還請發佈生成的JSON字符串,如腳本所返回的那樣; – feeela

+1

定義了'$ encoded_pa​​rams'並且使用了$ json_str? –

回答

0

這裏是我的建議。若要清理代碼,讓我們去掉了嵌入式的onclick,並給它一個ID:

$editpage->editFormTextTop = "<input type='button' id="requestBtn" />"; 

現在在腳本的頭部可以初始化值;

注:此代碼簡化

<script> 
window.onload = function() { 
    var url = "http://www.hello.com"; 
    var jsonString = "{\"format\": \"json\",\"event\": \"revert\",\"api_key\": \"<?php echo $wgAPIKey ?>\"}"; 
    // now we can assign the function to the button 
    document.getElementById("requestBtn").onclick = function() { 
     makePostRequest(url,json_string); 
    } 
} 
</script> 
0

我假設你的代碼的第二塊具有抄寫錯誤,並認爲「$ encoded_pa​​rams」 PHP變量應該是「$ json_str」。當該變量被擴展到HTML爲<input>元素,在它的雙引號字符會導致錯誤,因爲輸入元素看起來是這樣的:

<input type='button'value='hello' onclick='makePostRequest("http://www.hello.com", "{"format": "json", "event": "revert", "api_key": "something"}")' /> 

看看上面調用「makePostRequest() 「是搞砸了?帶有自己嵌入的雙引號字符的「encoded_pa​​rams」字符串最終會成爲格式不正確的字符串常量。

+0

對不起,沒有$ encoded_pa​​rams,你說得對,應該是$ json_str。 – tommycat

+0

如何解決?我需要以json格式發送數據 – tommycat

0

您的標題和內容文本不匹配。如果你想PHP變量傳遞給JavaScript簡單地做

var yourvar = '<?php echo $your_php_var; ?>';

相關問題