我有一个提示您输入密钥的表格。当用户插入密钥并单击提交时,它将在db中搜索密钥。如果找到了密钥,则必须自动下载与密钥相关的文件。我已经完成了直到使用AJAX和php与db进行验证。现在,我要自动下载文件。我怎样才能做到这一点? (最好能自动将其下载到php文件中)
JQUERY
$('#review-submit').on('click',function(){
var $secret_pin= $('#pin').val();
jQuery.ajax({
type : 'post',
url : ajax_review_plan_object.ajaxurl,
data : {
action : 'loadReviewPlansByAjax',
'search': $secret_pin
},
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success: function(response){
console.log(response);
response= response.match(/\d{2}$/);
if(response==1){
$('#empty_pin').fadeIn();
$('#invalid_pin').fadeOut();
$('#correct_pin').fadeOut();
$('#empty_table').fadeOut();
}else if(response==-1){
$('#empty_table').fadeIn();
$('#invalid_pin').fadeOut();
$('#correct_pin').fadeOut();
$('#empty_pin').fadeOut();
}else if(response==2){
$('#correct_pin').fadeIn();
$('#invalid_pin').fadeOut();
$('#empty_table').fadeOut();
$('#empty_pin').fadeOut();
}else if(response==3){
$('#invalid_pin').fadeIn();
$('#correct_pin').fadeOut();
$('#empty_table').fadeOut();
$('#empty_pin').fadeOut();
}
}
});
});
php
function loadReviewPlansByAjax(){
$search= $_POST['search'];
$args = array( 'post_type' => 'reviewplans' );
$loop = new WP_Query( $args );
if($loop->have_posts()){
while ( $loop->have_posts() ) : $loop->the_post();
// the_title();
$key = get_field('pin');
if($search== ''){
echo 1;
return;
} else if($key == $search){
echo 2;
return;
} else{
echo 3;
}
endwhile;
}else{
echo -1;
}
}
add_action( 'wp_ajax_loadReviewPlansByAjax', 'loadReviewPlansByAjax' );
add_action( 'wp_ajax_nopriv_loadReviewPlansByAjax', 'loadReviewPlansByAjax' );
function ajax_coming_soon_enqueues() {
wp_enqueue_script( 'review-plans-ajax-script', get_stylesheet_directory_uri() . '/framework/assets/js/review-plan-ajax.js', array( 'jquery' ), '1.0.0', true );
wp_localize_script( 'review-plans-ajax-script', 'ajax_review_plan_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'ajax_coming_soon_enqueues' );
答案 0 :(得分:0)
您必须创建一个PHP文件来验证密钥并开始下载流。这是我使用GET
方法上的键的示例。
if(isset($_GET["key"])){
$key = $_GET["key"];
//get key from database
//Validate the key
if($key == "key-from-database"){
if(file_exists("/path/to/file/" . $filename)){
$o = fopen("/path/to/file/" . $filename, "rb");
header("Content-Type: "); //Put mime type if you have it. You may left it empty
header('Content-Disposition: attachment; filename="'. $filename .'"'); //File name is important
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0, max-age=0');
header("Content-Transfer-Encoding: binary");
header('Pragma: public');
echo stream_get_contents($o);
fclose($o);
}
}
}
您也可以使用fopen()
之外的其他
答案 1 :(得分:0)
例如,您可以这样做:
正如您所说的,您可以进行ajax调用并进行验证,但我不会发布有关如何执行此操作的代码。