2012-01-19 27 views
0

我写了一个简单的jQuery函数从textarea提交数据。该脚本返回计算结果。 我收到一个错误,说recievedData没有定义。当用萤火虫调试时,我可以看到一个响应。使用jQuery与php脚本进行通信

这是我的jQuery函数。

$('#submitButton').click(
function(evt){ 
userCode = $('#answer').val(); 
$.ajax({ 
type : 'POST', 
url : 'scripts/php/check_answer.php', 
data : 'code=' + userCode, 
dataType : 'text', 
success : alert(recievedData) 
}); 
evt.preventDefault; 
}); 

这是PHP脚本

<?php 

//sample string, to be taken as input from the user program. 
$str = $_POST['code']; 
//the array with the weights 
$patterns = array (
    '/[:space]/' => 0, //whitespaces are free; need to add spaces too 
    '/[a-zA-Z]/' => 10, //characters 
    '/[0-9]/' => 500, //digits 
    '/[\+\-\/\*\%]/' => 10000, //arithmetic operators 
    '/[\<\>]/' => 5000, //relational operators 
    '/[\^\~\|\&]/' => 1000 , //bitwise operators 
    '/[\=]/' => 250, //assignment operator 
    '[\#]' => 100000 //No Macros 
); 

//default weight for characters not found is set here 
$default_weight = 55; 
$weight_total = 0; 
foreach ($patterns as $pattern => $weight) 
{ 
    $match_found = preg_match_all ($pattern, $str, $match); 
    if($match_found) 
    { 
    $weight_total += $weight * $match_found; 
    } 
    else 
    { 
    //this part needs to be fixed 
    $weight_total += $default_weight; 
    } 
} 

echo $weight_total; 

?> 
+1

它的表兄弟姐妹没有定义recievedData。 ;-)附注:如果您决定在您的应用程序中使用该名称,我建议将其拼写为“receivedData” - 并且我并不是sn or不驯或迂腐的;我们在应用程序中拼写错误地“收到”,它让我们困扰了数年!不是开玩笑! (必须向后兼容) –

回答

2

success:function(data){alert(data);} 
+0

这有效,还有一个疑问。如果我想调用一个命名函数而不是匿名函数,我需要做什么? – nikhil

+0

只是叫它而不是警报.. –

+1

只需提供函数名称,不加引号:'success:successFunction,...' – craigmj

1

另一种方式来发布使用jQuery

$('#submitButton').click(
function(evt){ 
userCode = $('#answer').val(); 

$.post("scripts/php/check_answer.php", {code: userCode}, 
    function(data) { 
    alert("Data Loaded: " + data); 
    }); 

evt.preventDefault; 
}); 
+0

这似乎更优雅。 – nikhil

相关问题