如果在减号之间,我有这个脚本与textarea中的keyup上的文本匹配。
$('#notes').keyup(function() { // notes is the id of the textarea
var regex = /\-([^\)]+)\-/gmi; // it gets the text between minus sign. Example: -text-
var myValue = $(this).val();
if(myValue.match(regex)){
var reference = myValue.match(regex);
$.ajax({
async: false,
type: "POST",
url: "scripts/script.php",
data: { "reference" : reference },
success: function(data) {
// I need to replace the text matched by the regex with data in the textarea.
// I need to stop the ajax calling after success or call it only if regex is matched
}
});
}
});
当正则表达式匹配文本时,它会向脚本发送ajax post调用,该脚本在数据库中搜索世界并返回定义。我需要用数据替换正则表达式匹配的文本,数据是由数据库提取的。
此外,我只想在匹配正则表达式时启动ajax POST调用。它只是第一次工作。在第一场比赛后,它仍然为每个键盘发送呼叫。
答案 0 :(得分:0)
Try the below code.
var triggerTime;
$("#notes").keyup(function() { // notes is the id of the textarea
clearTimeout(triggerTime);
var myValue = $(this).val();
triggerTime = setTimeout(function(){
var regex = /\-([^\)]+)\-/gmi; // it gets the text between minus sign. Example: -text-
if(myValue.match(regex)){
var reference = myValue.match(regex);
$.ajax({
async: false,
type: "POST",
url: "scripts/script.php",
data: { "reference" : reference },
success: function(data) {
// I need to replace the text matched by the regex with data in the textarea.
// I need to stop the ajax calling after success or call it only if regex is matched
}
});
}
}, 3000);// Call request in 3 second
});
This is the optimized version of your code. it will wait for users to complete, and in inactivity of 3 seconds, it will generate an Ajax call.
you can change the frequency to 2000 OR 1000 (2 second and 1 second respectively).
答案 1 :(得分:0)
我解决了将 contenteditable =" true" 添加到textarea的问题。 在最终的jquery代码下面:
var textInput = $("#notes"); // the ID of the textarea
var triggerTime;
$("#notes").keyup(function() { // notes is the id of the textarea
clearTimeout(triggerTime);
var myValue = $(this).text();
triggerTime = setTimeout(function(){
var regex = /\-([^\)]+)\-/gmi; // it gets the text between minus sign. Example: -text-
if(myValue.match(regex)){
var newValue;
var reference = myValue.match(regex);
$.ajax({
async: false,
type: "POST",
url: "scripts/parser.php",
data: { "reference" : reference },
success: function(data) {
newValue = data;
console.log(newValue);
$('.textarea').html(function() {
return $(this).text().replace(reference[0], '<strong>' + newValue + '</strong>');
});
}
});
}
}, 1000);// Call request in 1 second
});