如何将以下php更改为ajax?
<?php
$selectMSGs = 'SELECT * FROM group_messages WHERE group_id="'.$_GET["id"].'" ORDER BY msg_id DESC';
$selectMSGs2 = $connect->query($selectMSGs);
while ($rowMSGs = $selectMSGs2->fetch_assoc()) {
echo "<div class='lead MessageOfPerson'>";
echo "<div class='NameOfPerson'>";
echo "<p>";
echo $rowMSGs['msg_sender'];
echo "</div>";
echo "<div class='MessageText'>";
echo nl2br($rowMSGs['group_msg']);
echo "</p>";
echo "</div>";
echo "</div>";
echo "<hr>";
}
?>
我已经有一些已经在这个页面上运行的其他ajax课程(不是我自己的),是否可以将这个php与我当前的ajax和php文件结合起来?文件如下所示:
AJAX
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
function updateChat(){
$.ajax({
//TODO set localhost to the strato livechat file
url: "http://localhost:8080/LiveChat/LiveChat/code/php/groups/liveChat.php",
type: "get",
data: "msg_id="+$('#msg_id').val(),
dataType: "json",
success: function(response, status, http){
$.each(response, function(index, item){
$('#msg_id').val(item.msg_id);
//TODO update messages
});
},
error: function(http, status, error){
alert( 'Error updating chat, ' + error);
}
});
}
//auto update chat
setInterval( updateChat, 2000 );
</script>
PHP
<?php
// Lets fetch the value of msg_id
$data = $_REQUEST;
$msg_id = $data['msg_id'];
// Connect to MySQL Server TODO change to strato
$con = mysqli_connect( "localhost" , "root" , "" , "db2723249" );
// If msg_sender and group_msg is available then
// add it in table chats
if(
isset( $data['msg_sender'] ) &&
isset( $data['group_msg'] )
) {
$insert = "
INSERT INTO group_messages (group_id, group_msg, msg_sender)
VALUES( '".$data['msg_sender']."' , '".$data['group_msg']."' )
";
$insert_result = mysqli_query( $con , $insert );
}
$select = "SELECT *
FROM group_messages
WHERE msg_id > '".$msg_id."'
";
$result = mysqli_query( $con , $select );
$arr = array();
$row_count = mysqli_num_rows( $result );
if( $row_count > 0 ) {
while( $row = mysqli_fetch_array( $result ) ) {
array_push( $arr , $row );
}
}
// Close the MySQL Connection
mysqli_close( $con );
// Return the response as JSON
echo json_encode( $arr );
?>
答案 0 :(得分:-1)
好的,经过大约20个小时的工作后,我终于找到了怎么做(没有帮助:)!我能够合并新旧的ajax和php。
新的ajax成了
n
php成了:
require 'prime'
def max_number_primes(n)
return 0 if n < 2
t = 1
Prime.each_with_object([]) do |p, a|
tmp = p*t
return a if tmp > n
a << p
t = tmp
end
end
max_number_primes(50) #=> [2, 3, 5]
max_number_primes(50_000) #=> [2, 3, 5, 7, 11, 13]
max_number_primes(10_000_000_000) #=> [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]