我在Web类中为演示文稿创建了一个jQuery示例。我试图将我们做过的JavaScript程序转换为jQuery(对于有用的部分,如AJAX)。到目前为止,一切都很好。唯一的事情是:我无法弄清楚如何通过异步AJAX使用选项填充选择元素。使用AJAX和jQuery填充新的select元素
下面是程序的截图,所以我没有解释一切:http://imageshack.us/a/img829/5475/tableaui.png
所有的细胞都与它里面的文字输入元素,每一个修改是通过AJAX保存。最后一行是添加一个新行。当它被添加时,我添加行(带有table.appendChild(tr)),并在其中逐个创建所有元素。除了选择(一开始是空的,它们的内容是从数据库中提取的),一切都在那里工作。下面是一些代码(功能addLine,这就是所谓的内部阿贾克斯确认我的数据已经在数据库插入后):
input = document.createElement('select');
input.setAttribute('id', 'ID'+no_ligne+'_'+noms_champs[compteur]);
input.setAttribute('name', 'ID'+no_ligne+'_'+noms_champs[compteur]);
input.innerHTML = ajaxRequest('contenu_select', Array(no_ligne, valeurs[noms_champs[compteur]], noms_champs[compteur]));
ajaxRequest就是如下:
function ajaxRequest(action, data, ligneModifie, champModifie)
{
var AJAX_Controller = 'exer_7_carnet_formulaire.php';
var post_data = resultat_ajax = "";
// Set the posted data
if(action == 'update') {
//stuff
}
else if(action == 'insert') {
//stuff
}
else if(action == 'contenu_select') {
post_data += "noLigne=" + data[0] +
"&selected=" + data[1] +
"&type=" + data[2];
}
else {
post_data = null;
}
// Send the request
var jqxhr = $.ajax({
type: "POST",
url: AJAX_Controller+'?ajax=1&action='+action,
data: post_data,
success: function(reponse) {
resultat_ajax = processResponse(reponse, data, action);
}
});
return resultat_ajax;
}
gererReponse返回一个字符串我所有的选择(确认工作)。问题是:它在请求完成之前执行返回,因此它返回一个空字符串(因为resultat_ajax尚未定义)。我用setTimeout确认,然后变量在一秒钟后有预期的值。
我的问题是:如何填充我的选择在这种情况下?我之前创建的另一个版本(没有jQuery)像一个魅力一样,除了ajaxRequest函数外,其他代码都完全相同。这里是没有的jQuery谁曾经在那里而不是函数,这是工作(返回我的预期选项):
function ajaxRequest(action, data, ligneModifie, champModifie)
{
// Variables
var ReqTerminee = 4;
var ReponseOK_Local = 0;
var ReponseOK_Remote = 200;
var AJAX_Controller = 'exer_7_carnet_formulaire.php';
var xhr = getXMLHttpRequest();
var post_data = typeDeContenu = resultat_final = "";
// Monitoring request state
xhr.onreadystatechange = function() {
if (xhr.readyState == ReqTerminee)
if (xhr.status == ReponseOK_Local || xhr.status == ReponseOK_Remote)
resultat_final = gererReponse(xhr.responseText, data, action); // Here is the interesting part, this actually works and returns the right value.
else
alert("Code d'erreur: " + xhr.status);
};
// Sets the posted data
if(action == 'update')
{
// blahblah
}
else if(action == 'insert')
{
//blahblah
}
else if(action == 'contenu_select')
{
post_data += "noLigne=" + data[0] +
"&selected=" + data[1] +
"&type=" + data[2];
}
else
{
post_data = null;
}
// Sends the request
xhr.open("POST", AJAX_Controller+'?ajax=1&action='+action, false);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(post_data);
return resultat_final;
}
我有点失望,我不能与强大的jQuery比相同的结果我用简单的Javascript获得:/您是否知道如何才能获得良好的回报价值?
在此先感谢,任何帮助将不胜感激!
山姆
你说你正在使用的回报'ajaxRequest'函数的值? –