Coldfusion - 使用Ajax从另一个页面获取变量

时间:2016-03-02 04:18:14

标签: jquery html ajax variables coldfusion

我在通过Ajax从另一个ColdFusion页面获取变量时遇到问题。我有2个文件,分别是uploadForm.cfm和act_ajaxAddEditFile.cfm

在uploadForm.cfm文件中有Ajax代码。这个Ajax将提交表单。此ajax还将打开文件act_ajaxAddEditFile.cfm文件进行验证。验证完成后,我希望将变量#resultError#从act_ajaxAddEditFile.cfm传递给Ajax。

uploadForm.cfm(Ajax):

$jq('form').submit(function(e) {
  e.preventDefault();
  var type = $jq('#type').val();
  var form = document.getElementById('fileForm');
  var formData = new FormData(form);
  var xhr = new XMLHttpRequest();
  xhr.open('POST', 'pages/subactions/act_ajaxAddEditFile.cfm', true);
  xhr.send(formData);
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
      //I want to put variable #resultError# from act_ajaxAddEditFile.cfm here to do IF Statment.       
      var type = $jq('#type').val();
      $jq("#list" + type).load("pages/includes/inc_listFileResult.cfm", {
        type: type,
        qst_id: <cfoutput>#form.qst_id#</cfoutput> 
      }, function(response, status, xhr) {
        if (status == "error") {
          var msg = "Sorry but there was an error: ";
          $jq("#list" + type).html(msg + xhr.status + " " + xhr.statusText);
        }
      });
      $jq("#" + type).empty();
      $jq("." + type).removeClass('hide');
    }
  }
});

ajaxAddEdit.cfm(变量):

<cfif result.status EQ 'OK'>
  <cfoutput>upload FILE</cfoutput>
<cfelse>
  <cfoutput>Fail upload FILE</cfoutput>
  <cfset resultError = #result.error#>
</cfif>

1 个答案:

答案 0 :(得分:0)

如果它是字符串,您可以输出result.error,否则您可以使用某种编码来显示它。该文本将由ajax调用接收。然后你可以根据需要使用它。

<cfif result.status EQ 'OK'>
  <cfoutput>upload FILE</cfoutput>
<cfelse>
  <cfoutput>#result.error#</cfoutput>
</cfif>

话虽如此,您可以对代码进行一些更改。由于您使用的是jQuery,因此可以使用jQuery ajaxpost更改基本的JavaScript ajax调用。所以代码看起来更简单,如下所示。

$jq('form').submit(function(e) {
  e.preventDefault();
  var type = $jq('#type').val();
  $jq.post('pages/subactions/act_ajaxAddEditFile.cfm', $('#fileForm').serialize(), function(resp, status, jqxhr) {
    if (jqxhr.readyState == 4 && jqxhr.status == 200) {
      alert(resp);
      var type = $jq('#type').val();
      $jq("#list" + type).load("pages/includes/inc_listFileResult.cfm", {
        type: type,
        qst_id: '<cfoutput>#form.qst_id#</cfoutput>'
      }, function(response, status, xhr) {
        if (status == "error") {
          var msg = "Sorry but there was an error: ";
          $jq("#list" + type).html(msg + xhr.status + " " + xhr.statusText);
        }
      });
      $jq("#" + type).empty();
      $jq("." + type).removeClass('hide');
    }
  });
});