简体   繁体   English

jQuery Ajax请求在远程服务器上不起作用

[英]jquery ajax request not working on remote server

This is the first time i am trying to upload my work on a webhost from localhost.I have an ajax request to submit a form and get somre response from the server.But the success method is not triggering ,instead error method is triggering.Though it is working fine on localhost but for some reason it is not working on remote server .I think it is the url in the ajax request which is not getting the file though it is fine on localhost.What might be the reason for this and how i can fix this? 这是我第一次尝试从本地主机上将我的工作上传到Web主机上。我有一个Ajax请求来提交表单并从服务器获取更详细的响应。但是成功方法 没有触发,而是错误方法触发了。它在localhost上工作正常,但由于某种原因在remote server上不工作。我认为这是ajax请求中的url,尽管在localhost上很好,但没有获取文件。这可能是什么原因以及如何我可以解决这个问题吗?

i checked all the sql related with this ajax request.ALl working fine . 我检查了与此Ajax request.ALl相关的所有sql正常工作。

my domain name is :ezphp.tk 我的域名是:ezphp.tk

my question is is attaching the file location in the url is enough like i did or i had to treat it with something like http://mydomain/filepath ..... 我的问题是在url中附加文件位置就足够了,或者我必须用http:// mydomain / filepath .....来对待它。

ajax submission : Ajax提交:

 $.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');
           }
    });

verifyanswer.php file is : verifyanswer.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);

       }
   }

I think your problem is ajax cross domain. 我认为您的问题是ajax跨域。 You can set in php file by code: 您可以通过代码在php文件中设置:

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

Or reference here to resolve it 或参考这里解决

On your first php page when you call the ajax function try either of these two method: 在第一个php页面上,当您调用ajax函数时,请尝试以下两种方法之一:

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

This is method to call ajax after form submission: 这是在表单提交后调用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');
            }
        });

    }));

This is to call ajax through your custom function: 这是通过自定义函数调用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');
           }
        });

}

Add this line on top of your php page from where you are getting ajax json data: 从获取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);

first, you needs to check what exactly error you get from your ajax request, is this caused by cors or something else 首先,您需要检查从ajax请求中得到的确切错误是由于cors或其他原因引起的

change your jquery error function like below: 更改您的jquery错误函数,如下所示:

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

if you using shared hosting for your website, then you need to allow your web is can access from all origin using this, there are several ways to allow cross origin: 如果您为网站使用共享托管,那么您需要允许您的网站可以使用此方法从所有来源访问,有几种方法可以允许跨来源访问:

  1. in your resuested php file: added header to allow your acces origin using this : header("Access-Control-Allow-Origin: *"); 在您要求的php文件中:添加了标头,以允许您使用以下命令访问acces:header(“ Access-Control-Allow-Origin:*”);
  2. or you can config all your web using .httaccess 或者您可以使用.httaccess配置所有网站

for more info about cors enable, you can visit here enable-cors.org 有关cors enable的更多信息,您可以在此处访问enable-cors.org

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM