我需要为每个成功发送的消息获取JSON响应。我可以成功发送短信,但我无法从send_sms收到成功消息。PHP
<!-- index.php --->
<div id="responce"></div> <!-- respond sms sending -->
<form method="POST" onclick="return false">
<div class="form-group">
<label>Your Message</label>
<textarea class="form-control" rows="4" cols="100" id="message"
name="message" maxlength="70" required></textarea>
</div>
<button class="btn btn-primary" type="submit" name="submit"
onmousedown="start_sendig();" class="btn">Send</button>
</form>
//sendsms_button.js
function start_sendig() {
$("#responce").html("Please wait sending on process");
var message = $("#message").val();
var path_uri = "sms/send_sms.php";
$.ajax({
type: "POST",
url: path_uri,
data: {
message: message,
},
success: function (data) {
var json = $.parseJSON(data);
if (json.response == "success") {
$("#responce").html(
"Message Sent Successfully to " + json.current + " !!"
);
} else {
$("#responce").html("Error to Sent " + json.current + " !!");
}
},
});
}
AJAX 显示此错误
caught SyntaxError: Unexpected end of JSON input
at Function.parse [as parseJSON] (<anonymous>)
at Object.success (sendsms_button.js:13:20)
at i (jquery-3.2.1.min.js:2:28017)
at Object.fireWith [as resolveWith] (jquery-3.2.1.min.js:2:28783)
at A (jquery-3.2.1.min.js:4:14035)
at XMLHttpRequest.<anonymous> (jquery-3.2.1.min.js:4:16323)
<?php
//send_sms.php
include ("vendor/autoload.php");
include ("../config.php");
//insert record
$msg_sms = $_POST['message'];
mysqli_query ($con, "insert into sent_sms (message) values ('$msg_sms')");
if (isset($_POST['submit'])){
//select numbers
$result = mysqli_query($con, "SELECT mphone FROM members");
while ($row = mysqli_fetch_array($result)){
$numbers = $row['mphone'];
foreach (explode("+", $numbers) as $phone) {
$basic = new \Vonage\Client\Credentials\Basic("fxxxxx", "xxxxxxxxxxxxx");
$client = new \Vonage\Client($basic);
$response = $client->sms()->send(
new \Vonage\SMS\Message\SMS($phone, 'Hotel', $msg_sms)
);
$message = $response->current();
if ($message->getStatus() == 0) {
$data = array(
"response" => "success",
"current" => '+' . $phone
);
echo json_encode($data);
} else {
echo "<script>alert('The message failed with status: " . $message->getStatus() . "');</script>";
}
}
}
}
?>
我的目标是显示每个成功消息,如发送到+125332626成功
1条答案
按热度按时间62lalag41#
echo json_encode($data);
会产生问题。.将其保存在数组中,然后在循环后回显整个数组<script>
不是一个好主意。.好的方法是将错误作为编码JSON返回,然后 AJAX 成功函数上检查它-首先我们假设你的php代码和mysql连接正常。.
-第二个在 AJAX 中,你需要添加
dataType : "json"
。.-第三个还需要检查
isset($_POST['message'])
,而不是isset($_POST['submit'])
在php中
**注意:**使用 AJAX 时有很多原因会出错。我给了你一些代码的指导,让你知道如何思考和编码它。.但是你必须一步一步地检查 AJAX /php连接,以确切地知道什么是工作,什么是不.