dowdw44426 2019-08-02 15:13
浏览 136

为什么我可以使用直接HTML成功提交表单,但不使用AJAX? [重复]

I have been able to successfully submit a form to a remote CRM site to add a new account and get back a JSON reply string with the new accounts Id using a standard HTML page. However, it displays that response on a new blank page and I can't access the accountId, which I need for further processing. I have tried to follow several sites that showed how to convert that standard HTML form into a form where the page is submitted using ajax, with hopefully all of the proper parameters. When it attempts the submission, I get messages about:

[Error] Origin https://jwooten37830.com is not allowed by Access-Control-Allow-Origin.
[Error] XMLHttpRequest cannot load https://secure.engagemorecrm.com/api/2/AddAccount.aspx due to access control checks.
[Error] Failed to load resource: Origin https://jwooten37830.com is not allowed by Access-Control-Allow-Origin. (AddAccount.aspx, line 0)

However, the account was added correctly!

I created a test using a standard html page with the method="POST" and the action="https://server-site/AddAccount.aspx" as per the CRMs API where I provide the access keys in hidden text fields in the form. It submits correctly, adds the account, and returns the son string with the accountId, BUT I cannot access that string using this technique.

I then created the exact same form, but added the jQuery logic to submit the form using ajax, and get the errors stated above, even though the account gets added correctly, I get no son response due to the error.

This is the standard html form submission test:

<?php
require("header_footer.php");
$email = $_GET["email"];
$passwd = $_GET["password"];
$form = <<<EOT
<h1>Add Account</h1>
<hr />
<center>
<form method="POST" action="https://remote-crm.com/AddAccount.aspx" >
Email: <input type="text" name="email" value="" autofocus /><br />
Password:<input type="password" name="password" value="" /><br />
<input type="hidden" name="apipassword" value="a password" />
<input type="hidden" name="apiusername" value="a user id" />
<input type="hidden" name="group" value="RE FreeTrial" />
<input type="hidden" name="affiliatecode" value="1001" />
<br />
<input type="submit" name="submit" value="Submit" id="submit" />
</form>
EOT;

echo page_header();
echo $form;
echo git_footer();
echo "</center>";
echo "</body>";
echo "</html>";

Here is the code trying to use ajax to do the submission so I can retrieve the accountId from the son response for further processing:

<?php
session_start(); // Start a session for storing things
require("header_footer.php");
$email = $_GET["email"];
$form = <<<EOS
 <style>
    #form label{float:left; width:140px;}
    #error_msg{color:red; font-weight:bold;}
 </style>

<h1>Your email is confirmed.  Please complete the form</h1>
<hr />
When the submit button is pressed, the account will be created using the information from the form and the master api key to add the account to the trial group.  At the end of the addition, the user will be redirected to EngageMoreCRM to login.
<hr/>
<form id="form" action="https://remote-crm.com/AddAccount.aspx">
<table>
<tr><td>Email:</td><td>
<input type="text" name="email" value="$email" /></td></tr>
<tr><td>Password: </td><td><input type="password" name="password" value="" id="password"/></td></tr>
<tr><td>Confirm: </td><td><input type="password" value="" name="confirm" id="confirm_password"/></td></tr>
</table>
<input type="hidden" name="response_type" value="json" />
<input type="hidden" name="apipassword" value="a password" />
<input type="hidden" name="apiusername" value="a user id" />
<input type="hidden" name="group" value="RE FreeTrial" />
<input type="hidden" name="affiliatecode" value="1001" />
<br />
<input type="submit" id="submit_id" name="submit" value="Submit" disabled="disabled"/>
</form>

<script src="https://code.jquery.com/jquery-2.1.0.min.js"></script>
 <script>
    $(document).ready(function(){
// This starts the section to be sure passwords are filled in and match
        var submitBtn = $("#submit_id");
        var passwordBox = $("#password");
        var confirmBox = $("#confirm_password");
        var errorMsg =  $('<span id="error_msg">Passwords do not match.</span>');

        // This is incase the user hits refresh - some browsers will maintain the disabled state of the button.
        submitBtn.removeAttr("disabled");

        function checkMatchingPasswords(){
            if(confirmBox.val() != "" && passwordBox.val != ""){
                if( confirmBox.val() != passwordBox.val() ){
                    submitBtn.attr("disabled", "disabled");
                    errorMsg.insertAfter(confirmBox);
                }
            }
        }

        function resetPasswordError(){
            submitBtn.removeAttr("disabled");
            var errorCont = $("#error_msg");
            if(errorCont.length > 0){
                errorCont.remove();
            }
        }


        $("#confirm_password, #password")
             .on("keydown", function(e){
                /* only check when the tab or enter keys are pressed
                 * to prevent the method from being called needlessly  */
                if(e.keyCode == 13 || e.keyCode == 9) {
                    checkMatchingPasswords();
                }
             })
             .on("blur", function(){
                // also check when the element looses focus (clicks somewhere else)
                checkMatchingPasswords();
            })
            .on("focus", function(){
                // reset the error message when they go to make a change
                resetPasswordError();
            })
// This ends the password checking section.  Left in in case someone sees that it is interfering somehow.
            //callback handler for form submit
           $("#form").submit(function(e)
           {
           var postData = $(this).serializeArray();
           var formURL = $(this).attr("action");

           $.ajax(
           {
            url : formURL,
            type: "POST",
            crossDomain: true,
            data : postData,
            dataType: "json",  // Can this be the problem?
         success:function(data, textStatus, jqXHR) 
         {
           //data: return data from server
            alert('it worked');
            alert("Result: "+data.result+", Message: "+data.message);
          },
          error: function(jqXHR, textStatus, errorThrown) 
         {
            //if fails   
            alert('it didnt work');   
          }
        });
        e.preventDefault(); //STOP default action
//        e.unbind(); // This was causing an undefined error.  Not sure if necessary or needed or why it was here.
    });

  $("#form").submit(); //Submit  the FORM

    });
  </script>
EOS;
 echo page_header();
  echo $form;
  echo git_footer();
  echo "</body>";
  echo "</html>";
?>

Expected to receive a result containing:

data = { "accountid": "123", "authentication":"xyzzy"}

Instead alert comes up with "It failed" and in the Web Console I get

[Error] Origin https://jwooten37830.com is not allowed by Access-Control-Allow-Origin.
[Error] XMLHttpRequest cannot load https://secure.engagemorecrm.com/api/2/AddAccount.aspx due to access control checks.
[Error] Failed to load resource: Origin https://jwooten37830.com is not allowed by Access-Control-Allow-Origin. (AddAccount.aspx, line 0)

What am I not doing right in the ajax submission that causes me to not receive the json response in the result object that gets output to a blank page when I use the standard html approach?

</div>
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
    • ¥20 易康econgnition精度验证
    • ¥15 msix packaging tool打包问题
    • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
    • ¥15 python的qt5界面
    • ¥15 无线电能传输系统MATLAB仿真问题
    • ¥50 如何用脚本实现输入法的热键设置
    • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
    • ¥30 深度学习,前后端连接
    • ¥15 孟德尔随机化结果不一致