2017-03-06 52 views
0

我試着做,做了這個功能callFunction();試圖使一個函數執行功能

我試圖使用AJAX

一個PHP文件執行JS的功能,因爲我有AJAX responseText我試着使用

<script type="text/javascript"> callFunction(); </script>

,但它沒有工作,我試着做這樣的事情

function exec(func , arg) { 
    func(arg); // executes the function 
} 

,如果這樣的事情是不存在的,我怎麼能說與AJAX功能從一個PHP請求(通過GET方法)

我得到的錯誤,當我嘗試它是

FUNC不是函數

JS AJAX代碼

   var emailVal = document.getElementById("email").value; 
       var passVal = document.getElementById("password").value; 
       var uVal = document.getElementById("username").value; 
       var busVar = document.getElementById("businessname").value; 
       var firstVal = document.getElementById("firstname").value; 
       var params = "email=" + emailVal + "&password=" + passVal + "&businessname="+busVar + "&username="+uVal+"&firstname="+firstVal; 
       var url = "business.php"; 
       http = new XMLHttpRequest(); 
       http.open("POST", url, true); 

       //Send the proper header information along with the request 
       http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 

       http.onreadystatechange = function() { //Call a function when the state changes. 
        if(http.readyState == 4 && http.status == 200) { 
         console.log(http.responseText); 
         exececc(http.responseText , null); 
        } 
       } 

       http.send(params); 

PHP代碼

echo '<script type="text/javascript"> callFunction(); </script>';

+0

你需要更多的指定問題。與我們分享更多的代碼等等,很難說出你想在這裏完成什麼。 –

+0

當然!我目前正在添加代碼 –

回答

0

好吧,我想我看到的問題,你傳遞一個字符串到executeFunction()

在這種情況下,試試這個,確保您分配給變量的值fnName & params是字符串並且沒有JSON對象。例如,您可能需要執行data [「fnName」]從數據JSON對象中提取函數名稱。您可以通過將它們轉儲到控制檯來檢查數據類型。

function say($something) { 
 
    console.log($something); 
 
    return; 
 
} 
 

 
var fnName = "say"; 
 
var params = "Hello world" 
 

 
window[fnName](params);

+0

我認爲那有效嗎?好東西! – Brad

0

請確保您傳遞一個有效的函數名,以執行它的功能,就像這樣:

function saySomething($something){ 
 
\t console.log($something); 
 
} 
 

 
function executeFunction(func,arg){ 
 
\t func(arg); 
 
} 
 

 

 
executeFunction(saySomething,"Yay, it works!");

+0

我複製了你的代碼,它給了我同樣的錯誤 –

+0

'func不是一個函數' –

+0

這必須是你要麼傳遞它錯誤的名稱,在它的saySomething作爲第一個arg當調用executeFunction時。或者你正在聲明函數的文件沒有包含在你打這個電話之前 – Brad