【问题标题】:Communicating with a php script using jQuery使用 jQuery 与 php 脚本通信
【发布时间】:2012-01-19 05:35:56
【问题描述】:

我编写了一个简单的 jQuery 函数来从文本区域提交数据。该脚本返回计算结果。 我收到一条错误消息,指出未定义 recievedData。 使用 firebug 进行调试时,我可以看到响应。

这是我的 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;

?>

【问题讨论】:

  • 这是因为没有定义 recievedData。 ;-) 旁注:如果您决定在您的应用程序中使用该名称,我建议将其拼写为“receivedData”——而且我不是流氓或迂腐;我们在申请中拼错了“received”,它困扰了我们多年!不是开玩笑! (与向后兼容性有关)

标签: php jquery ajax


【解决方案1】:

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

【讨论】:

  • 那行得通,还有一个疑问。如果我想调用命名函数而不是匿名函数,我需要做什么?
  • 只提供函数名,不用引号:success: successFunction, ...
【解决方案2】:

另一种使用 jquery 发帖的方式

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

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

evt.preventDefault;
});

【讨论】:

    猜你喜欢
    • 2016-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-06
    • 1970-01-01
    • 2018-07-30
    • 1970-01-01
    相关资源
    最近更新 更多