我的PHP
<?php
$from = $_POST['from'];
$to = $_POST['to'];
$word = $_POST['word'];
function strProper($str) {
$noUp = array('a','an','of','the','are','at','in');
$str = trim($str);
$str = strtoupper($str[0]) . strtolower(substr($str, 1));
for($i=1; $i<strlen($str)-1; ++$i) {
if($str[$i]==' ') {
for($j=$i+1; $j<strlen($str) && $str[$j]!=' '; ++$j); //find next space
$size = $j-$i-1;
$shortWord = false;
if($size<=1000) {
$theWord = substr($str,$i+1,$size);
for($j=0; $j<count($noUp) && !$shortWord; ++$j)
if($theWord==$noUp[$j])
$shortWord = true;
} else{
$str = substr($str, 0, $i+1) . strtoupper($str[$i+1]) . substr($str, $i+2);
}
}
$i+=$size;
}
return $str;
}
if(file_exists("$from-$to.txt")){
$file = file("$from-$to.txt", FILE_IGNORE_NEW_LINES);
} else{
$file = null;
}
$array = array();
$return = array();
if($file != null){
foreach($file as $line){
if(!empty($line)){
$words = explode("=", $line);
$results = explode("|", $words[1]);
$rest = explode("|", $words[1]);
array_shift($rest);
$array[$words[0]] = $results[0];
$final = strProper(strtr(strtolower($word), $array));
$final = trim($final);
} else{
$final = null;
}
}
$return['final'] = $final;
$return['others'] = $rest;
echo json_encode($return);
}
我的AJAX电话:
$("#translate_word").keyup(function(e){
var from = $("#translate_from").val();
var to = $("#translate_to").val();
$("#translate_result").html($(this).val());
$.ajax({
type: "POST",
url: "translate.php",
data: {word: $(this).val(), from: from, to: to},
success: function(html){
if(html !== ""){
var obj = $.parseJSON(html);
console.log(obj);
$("#translate_result").text(obj.final);
if(typeof obj.others === 'object'){
$.each(obj.others, function(index, val){
$("#translate_others").html($("#translate_others").html() + val + "<br />");
});
} else{
$("#translate_others").html($("#translate_others").html() + obj.others + "<br />");
}
}
}
});
});
但是当我运行该功能时,它说:
未捕获的SyntaxError:意外的令牌&lt; jquery.min.js:4个
n.parseJSON jquery.min.js:4
$ .ajax.success(index):135
j jquery.min.js:2
k.fireWith jquery.min.js:2
x jquery.min.js:4
b
但每当我从第43行的PHP中删除函数strProper
时,它都不会抛出错误,一切正常。