jquery ajax 请求在远程服务器上不起作用

jquery ajax request not working on remote server

本文关键字:服务器 不起作用 ajax 请求 jquery      更新时间:2023-09-26

这是我第一次尝试从本地主机在虚拟主机上上传我的作品。我有一个 ajax 请求提交表单并从服务器获得 somre 响应。但是成功方法不是触发,而是错误方法触发。虽然它在localhost上运行良好,但由于某种原因它不适用于remote server.我认为这是 ajax 请求中的 url,尽管在本地主机上很好,但它没有获取文件。这可能是什么原因,我该如何解决这个问题?

我检查了与此 Ajax 请求相关的所有 SQL。全部工作正常。

我的域名是:ezphp.tk

我的问题是,在 URL 中附加文件位置就足够了,就像我所做的那样,或者我不得不用类似 http://mydomain/filepath 的东西来处理它......

阿贾克斯提交:

 $.ajax('../includes/verifyanswer.php',{
        data:{
            'answer_body': CKEDITOR.instances.content.getData(),
            'userpost_post_id': <?php echo $postid;?>,
            'users_user_id': <?php echo $userdata->user_id; ?>
             },
        type:"POST",
        dataType:'json',
        success:function(response){


           alert('bal');
             var obj=response;
           alert(obj[0].answer_body);
              $('#mainanswer').hide();
              $('#answerform').hide();
              $('#answerthisquestion').show();
              var str="<div class='styleanswer' >"+obj[0]['answer_body']+"</div><div class='customcmntholder'></div><span id='customcomment' class='cmnt' onclick='letmecomment(event);'>Add a Comment...</span><form action='<?php echo $_SERVER['PHP_SELF']; ?>' method='post'  name='cmntform'> <textarea  data-id="+obj[0]['answer_id']+" class='customcmntform' placeholder=' add a comment......' ></textarea></form><hr>";
              $('#answerwrapper').append(str);
                $('#answerwrapper pre code').each(function(i, block) {
                   hljs.highlightBlock(block);
              });
        },
        error:function(response){
              alert('there are some errors');
           }
    });

验证答案.php文件是:

 require_once '../core/init.php';
   $answer=$_POST['answer_body'];
   $post_id=$_POST['userpost_post_id'];
   $answerer=$_POST['users_user_id'];
   if(isset($answer,$post_id,$answerer)){
     if(!empty($answer) && !empty($post_id) && !empty($answerer)){
           $db=DB::getInstance();
           $result=$db->post_and_fetch("CALL login.post_and_fetch_ans(?,?,?)",array($answer,$post_id,$answerer))->result();
                echo json_encode($result);
       }
   }

我认为你的问题是ajax跨域。您可以通过代码在 php 文件中设置:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');  

或参考此处解决它

首先,您需要检查从 ajax 请求中得到的确切错误,这是由 cors 还是其他原因引起的

更改您的 jQuery 错误函数,如下所示:

error: function(xhr, status, error) {
  var err = eval("(" + xhr.responseText + ")");
  alert(err.Message);
}

如果您为您的网站使用共享主机,那么您需要允许您的网络可以从所有来源访问 使用此,有几种方法可以允许跨源:

  1. 在你恢复的 PHP 文件中:添加了标头以允许你的 acces origin 使用这个 : header("访问控制-允许-原点:*");
  2. 或者您可以使用 .httaccess 配置您的所有网络

有关 CORS Enable 的更多信息,您可以访问此处 enable-cors.org

在调用 ajax 函数时的第一个 php 页面上,请尝试以下两种方法之一:

 <!-- This is your form -->
 <form name="yourForm" id="yourForm" method="post" action="http://yourdomain.com/includes/verifyanswer.php" novalidate >
 <input type="submit"  />
 </form>

这是在表单提交后调用 ajax 的方法:

$('#yourForm').on('submit',(function(e) {
        e.preventDefault();
        var formData = $(this).serialize();
        $.ajax({
            type:'POST',
            url: $(this).attr('action'),
            dataType: "json", 
            data:formData,
            processData: false,
            success:function(data){
            alert(data);
            },
            error: function(data){
                alert('there are some errors');
            }
        });
    }));

这是通过自定义函数调用 ajax:

function testFunction()
{
    var yourparam1 = "abc";
    var yourparam2 = "123";
        $.ajax({
          type: "POST",
          url: "http://yourdomain.com/includes/verifyanswer.php",
          dataType: "json",
          data: {
                   param1 : yourparam1,
                   param2 : yourparam1
                },
          success: function(data) {
                alert(data);
          },
           error: function(data){
                alert('there are some errors');
           }
        });
}

在从中获取 ajax json 数据的 php 页面顶部添加此行:

// PHP headers (at the top)
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");
$output = "Hello world";
echo json_encode($output);