gpt4 book ai didi

php - Twilio Ajax 响应始终触发 'Fail' ,尽管成功调用电话

转载 作者:行者123 更新时间:2023-12-01 08:35:08 25 4
gpt4 key购买 nike

我正在尝试制作一个简单的 Twilio 应用程序,我大致遵循本教程:https://www.twilio.com/docs/voice/tutorials/click-to-call-php不过,我稍微调整和简化了它以满足我的需要,尽管问题元素似乎没有任何不同。

Ajax :

$('#twilio_click_form').on('submit', function(e) {
// Prevent submit event from bubbling and automatically submitting the form
e.preventDefault();
// Call our ajax endpoint on the server to initialize the phone call
$.ajax({
url: '[...]/twilio_click_call',
method: 'POST',
dataType: 'json',
data: {
userPhone: $('#userPhone').val()
}
}).done(function(data) {
// The JSON sent back from the server will contain a success message
alert(data.message);
}).fail(function(error) {
alert('error');
alert(JSON.stringify(error));
});
});

PHP:

public function twilio_click_call()
{
$twilio_creds = array(
'TWILIO_ACCOUNT_SID' => 'xxxx',
'TWILIO_AUTH_TOKEN' => 'xxxx',
'TWILIO_NUMBER' => 'xxxx'
);

$userPhone = $this->input->post('userPhone');

// Create authenticated REST client using account credentials
$client = new Twilio\Rest\Client(
$twilio_creds['TWILIO_ACCOUNT_SID'],
$twilio_creds['TWILIO_AUTH_TOKEN']
);

try
{
$client->calls->create($userPhone, $twilio_creds['TWILIO_NUMBER'],
array("url" => 'http://demo.twilio.com/docs/voice.xml')
);
}
catch (Exception $e)
{
// Failed calls will throw
return $e;
}

return array('message' => 'Call incoming!');
}

调用启动并完美运行,但是 Ajax 响应总是触发 .fail(),而不是 .done() 方法 - 无法确定原因。

最佳答案

您的代码中有两处错误。1.在ajax调用中,您已将datType定义为json,因此它也期望contentType为json,但您返回的是第一期的数组2. 您在 url 内调用 url

使用此代码:

public function twilio_click_call()
{
$twilio_creds = array(
'TWILIO_ACCOUNT_SID' => 'xxxx',
'TWILIO_AUTH_TOKEN' => 'xxxx',
'TWILIO_NUMBER' => 'xxxx'
);

$userPhone = $this->input->post('userPhone');

// Create authenticated REST client using account credentials
$client = new Twilio\Rest\Client(
$twilio_creds['TWILIO_ACCOUNT_SID'],
$twilio_creds['TWILIO_AUTH_TOKEN']
);

try
{
$client->calls->create($userPhone, $twilio_creds['TWILIO_NUMBER'],
array("url" => 'http://demo.twilio.com/docs/voice.xml')
);
}
catch (Exception $e)
{
// Failed calls will throw
echo json_encode(array($e));
}

echo json_encode(array('message' => 'Call incoming!'));
}

关于php - Twilio Ajax 响应始终触发 'Fail' ,尽管成功调用电话,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57166954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com