我的javascript如下;
$.ajax({
type: "POST",
url: "ajax.php",
data: {
filename: $("#title1").html()
},
success: function(response){
$cell1.css("background-image", "url('pdfthumb/" + response + ".jpg')");
}
});
$.ajax({
type: "POST",
url: "ajax.php",
data: {
filename: $("#title2").html()
},
success: function(response){
$cell2.css("background-image", "url('pdfthumb/" + response + ".jpg')");
}
});
$.ajax({
type: "POST",
url: "ajax.php",
data: {
filename: $("#title3").html()
},
success: function(response){
$cell3.css("background-image", "url('pdfthumb/" + response + ".jpg')");
}
});
$.ajax({
type: "POST",
url: "ajax.php",
data: {
filename: $("#title4").html()
},
success: function(response){
$cell4.css("background-image", "url('pdfthumb/" + response + ".jpg')");
}
});
以及更多......每当我想要结果时,我都需要ajax,这使得脚本变得冗长。有没有办法缩短代码?
您可以看到我的完整代码 here 。如果有人纠正我的代码,我将非常感激。
感谢advence ..
blasteralfred
答案 0 :(得分:2)
为你做一个函数怎么样?
function updateImage(title, cell) {
$.ajax({
type: "POST",
url: "ajax.php",
data: {
filename: title
},
success: function (response) {
cell.css("background-image", "url('pdfthumb/" + response + ".jpg')");
}
});
}
然后你可以这样称呼:
updateImage($('#title1').html(), $cell1);
updateImage($('#title2').html(), $cell2);
updateImage($('#title3').html(), $cell3);
updateImage($('#title4').html(), $cell4);
答案 1 :(得分:0)
function myJax(file,successBlock){
$.ajax({
type: "POST",
url: "ajax.php",
data: {
filename: file
},
success: function(response,successBlock){
successBlock.css("background-image", "url('pdfthumb/" + response + ".jpg')");
}
});
};
myJax($("#title1").html(),$cell1);
myJax($("#title2").html(),$cell2);
// etc...
答案 2 :(得分:0)
确实有很多方法可以缩短您必须编写的代码行数。我将首先在包装器中包装$ .ajax函数并使用该包装器来完成您的工作。像
这样的东西function myAjax(mdata,mcallback){
$.ajax({
type: "POST",
url: "ajax.php",
data: mdata,
success: function(response){
mcallback(response);
}
});
}
You can then go
myAjax($("#title3").html(),callback);
答案 3 :(得分:0)
拥有像这样的javascript函数
function ajax_call(urlString,title,cell)
{
ret_val="";
$.ajax
(
{
type: "POST",
url: urlString,
data: {
filename: $("#"+title).html()
},
success: function(response){
$("#"+cell).css("background-image", "url('pdfthumb/" + response + ".jpg')");
}
);
return ret_val;
}
然后像这样调用函数
ajax_call("http://xyz.com","title1","cell1");
ajax_call("http://xyz.com","title2","cell2");
为此,你应该找到一种方法来识别cell1,cell2 ......我假设它将有一个html id来识别
答案 4 :(得分:0)
如果所有呼叫都是紧接着完成的,那么可能值得尝试在一次呼叫中获取一个Url列表,以获取所提供的标题列表。即在需要时只进行一次ajax调用。
答案 5 :(得分:0)
我使用以下脚本解决了这个问题;
<script type="text/javascript">
function updateBackground(cellId, titleId) {
$.ajax({
type: "POST",
url: "ajax.php",
data: {
filename: $("#"+titleId).html()
},
success: function(response){
$("#"+cellId).css("background-image", "url('pdfthumb/" + response + ".jpg')");
}
});
}
$(document).ready(function(){
updateBackground("res1", "title1");
updateBackground("res2", "title2");
updateBackground("res3", "title3");
updateBackground("res4", "title4");
});
</script>