jquery - 如何将ajax请求发送到laravel控制器公共功能
问题描述
我有从 laravel 控制器加载数据的页面,有一个按钮可以调用 jquery 函数,
并且按钮值中有一个电话号码,所以我需要向该号码发送短信,
在这里我附上了我使用的代码,
SMS网关功能齐全,我出于安全原因删除了个人数据,
关联
<i><a class="btn btn-info" id="Confirm2" value="{{$padd->ContactNum02}}">Confirm</a></i>
JQ码
<script type="text/javascript">
$(document).ready(function(){
$("#Confirm2").click(function(){
$("#ConfirmNo02input").show();
$("#Confirm2").hide();
OTPSend();
var PhoneNum = $("#Confirm2").val();
function OTPSend( PhoneNum) {
$.ajax({
url: 'OTP_send',
type: 'POST',
datatype:'json',
data:{SearchKey:PhoneNum},
})
.done(function(data) {
alert("run")
console.log("run");
})
.fail(function() {
alert("fail")
console.log("error");
})
}
});
});
</script>
路线
Route::post('/OTP_send', 'ServicesController@OTP' )->name('OTP_send');
控制器文件
public function OTP(Services $services)
{
$testNum='0753505625';
$api_instance = new SmsApi();
$user_id = "xxxxx";
$api_key = "xxxxxxxxxxxxxxx";
$message = "test SMS";
$PhoneNo=ltrim( $testNum , "0");
$to ="94".$PhoneNo;
$sender_id = "NotifyDEMO";
try {
$api_instance->sendSMS($user_id, $api_key, $message, $to, $sender_id);
} catch (Exception $e) {
echo 'Exception when calling SmsApi->sendSMS: ', $e->getMessage(), PHP_EOL;
}
return response()->json(['message' => 'successfull'],200);*/
}
此代码不起作用,您能帮帮我吗
解决方案
您的代码中有多个问题。
首先像这样更改您的 HTML,您需要一个按钮而不是链接。
<i><button class="btn btn-info" id="Confirm2" value="{{$padd->ContactNum02}}">Confirm</button></i>
将您的 Javascript 更改为此
$(document).ready(function(){
$(document).on('click','#Confirm2',function(e){
e.preventDefault();
$("#ConfirmNo02input").show();
$("#Confirm2").hide();
$.ajax({
url: 'OTP_send', // URL for the function
method:"POST",
data:{
phone:$("#Confirm2").val()
},
success:function(result){
if(result.status == 'success'){
alert('ran');
}
else{
alert('failure');
}
}
});
});
最后将您的控制器更改为此。
public function OTP(Request $request){
$testNum='0753505625';
// use this to send the text on number coming from the button
// $testNum = $request->phone;
$api_instance = new SmsApi();
$user_id = "xxxxx";
$api_key = "xxxxxxxxxxxxxxx";
$message = "test SMS";
$PhoneNo=ltrim( $testNum , "0");
$to ="94".$PhoneNo;
$sender_id = "NotifyDEMO";
try{
$api_instance->sendSMS($user_id, $api_key, $message, $to, $sender_id);
$response['status'] = 'success';
}
catch(Exception $e) {
echo 'Exception when calling SmsApi->sendSMS: ', $e->getMessage(), PHP_EOL;
}
return $response;
}
最后,确保您在 ajax 中传递的路由正确指向控制器的此功能。
推荐阅读
- ios - Intune 托管与非托管设备
- r - 基于R中的列基于间隔制作垃圾箱
- c# - 在 Visual Studio 中找不到 Console.Writeline
- azure - 是否可以使用 Azure 搜索 SDK 创建新的 Azure 搜索服务?
- kubernetes - 如何使用 nginx 入口正确设置自定义标头?
- android - 如何通过 Intent 检索和分离数组中传递的多个数据从一个活动到另一个活动
- flask - 烧瓶文件下载并上传到谷歌驱动器
- amazon-web-services - 如何在 cloudfront lambda@Edge 函数中访问 S3 存储桶对象?
- angular - VS 2017 & Angular /w 没有 dist 或 wwwroot
- python-2.7 - 如何在谷歌应用引擎中正确导入 requests_toolbelt?