这是一个很好的链接。它从Google API导入GMail联系人:
链接
<a id='gmailInvite' class="button icon chat" href="<?php echo site_url('main/gmail_invite'); ?>"><span>Import GMail Contacts</span></a>
我正尝试通过div
按钮重复此功能。
Div按钮
<div class="gmailbutton" onclick="importGMailContacts()"><span class="textwhite">Import Gmail Contacts</span></a>
function importGMailContacts()
{
var form_data = "";
$.ajax({
url: "<?php echo site_url('main/gmail_invite'); ?>",
type: 'POST',
data: form_data,
success: function(msg) {
alert(msg)
return true;
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
}
});
}
当我点击div按钮时,它转到控制器方法。但没有任何反应。
如何从div按钮模拟href post
?
答案 0 :(得分:1)
window.location = "<?php echo site_url('main/gmail_invite'); ?>"
。要发送浏览器所遵循的POST,您需要使用适当的操作创建一个FORM并提交它。
答案 1 :(得分:0)
只需使用JQuery“click”功能,这样您就可以操纵任何元素并执行您需要做的任何事情(可以是GET,POST或自定义操作)。例如,click函数可用于提交表单,表现为“链接”,或者只是触发Ajax调用。
以下是示例函数:
$('#gmailbutton').click(function(){
var form_data = 'WHATEVER DATA YOUR COLLECTING'
$.ajax({
//the type of call it can be GET or POST
type:'POST',
//If it is a static URL you dont need to echo with PHP
//just write it directly
url:'main/gmail_invite/ajax.sample.call.php', //or whatever you php file is called
//if you want to receive the data as html,json,xml
dataType:'json',
cache:false,
beforeSend:function(x){
//use this only if the response is a JSON object
if(x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
}
}).done(function(response){
//use "done" rather than "success", as "success" has been deprecated from JQUERY
console.log( response );
//no need to return, the ajax returns the call by default
}).fail(function(jqXHR, textStatus, errorThrown){
console.log( jqXHR );
console.log( textStatus );
console.log( errorThrown );
});
});