这里有一个场景:我正在构建一个Wordpress插件来管理我参与的一些调查研究。项目管理员能够从WP管理界面上传csv文件。在客户端,当文件上传时,它会遍历文件的每一行,提取关于用户的必要信息,然后进行AJAX调用,将参与者添加到项目中。我决定在客户端解析csv文件,然后逐个提交ajax请求,以便在每次返回时更新一个进度条。javascript如下所示:
$( '#csv_upload_button' ).click( function() {
// declare the necessary variables
var f = $( '#csv_file_input' )[0].files[0],
fr = new FileReader,
rows, headers, dialog, count, remaining;
// when the file loads
fr.onload = function() {
// get the rows, the count, number remaining to process, and headers
rows = fr.result.split( "\n" );
remaining = count = rows.length - 1; // -1 to account for header row
headers = $.trim( rows[0] ).split( ',' );
// create the dialog box to show the progress bar
dialog = $( '<div></div>' )
.html(
'<p>Loading...</p>' +
'<p><progress id="csv_upload_progress" max="' + count +
'" min="0" value="0"></p>' )
.dialog( { modal: true; } );
// then for each row in the file
$( rows ).each( function( i, r ) {
// create an object to hold the data
var data = {}, row = $.trim( r ).split( ',' ), j;
if ( i > 0 ) { // data starts on the second row
// map the data into our object
for ( j = 0; j < headers.length; j++ ) {
data[ headers[ j ] ] = row[ j ];
}
// send it to the server
$.post(
ajaxurl,
{
action: 'import_panel_member',
data: data,
postid: $( '#post_ID' ).val()
},
function( result ) {
var prog = $( '#csv_upload_progress' );
prog.attr( 'value', prog.attr( 'value' ) + 1 );
if ( 0 == --remaining ) {
// stuff to do when everything has been loaded
}
}
);
}
});
};
// read the csv file
fr.readAsText( f );
});PHP看起来如下所示:
function import_panel_member() {
header( 'content-type: application/json' );
// get the variables sent from the client
$postid = $_POST[ 'postid' ];
$data = $_POST[ 'data' ];
/*
* ...do other things involving talking to a 3rd party server...
*/
// get the WP meta data variable to be updated
$participants = get_post_meta( $postid, '_project_participants', true );
// modify it
$participants[] = $data;
// update the database
update_post_meta( $postid, '_project_participants', $participants );
// return a message to the client
echo json_encode( (object) array( 'success' => 1, 'message' => 'added' ) );
exit;
}问题是,由于这些请求是异步发生的,所以_project_participants元数据字段似乎只被要处理的最后一条记录更新。换句话说,只有列表中的最后一个人出现在参与者列表中。以下是我尝试过的一些事情:
$.post() $.ajax() 更改为$.ajax()并设置 async: false
这是可行的,但速度要慢得多(由于同步调用),而且由于某种原因,它会阻止我的对话框在所有ajax调用完成后才显示出来。所以,也许我是贪婪的,只想要我的蛋糕,并把它也吃掉。我如何利用异步请求的速度,让我有机会用进度条给用户反馈,而不让自己搞砸服务器上的并发问题?
发布于 2012-10-31 00:46:26
我想通了。答案是这两种方法的混合。我可以使用一系列的$.post()调用来完成在异步模式下工作更好的部分,然后上传整个csv来完成在同步模式下工作更好的部分。如果不把所有的解释都打出来,就不可能搞清楚这一点!
https://stackoverflow.com/questions/13149708
复制相似问题