假设我有一个登录对象,当我对“登录”进行获取请求时,我发送了登录对象,并且在JSP页面中,我使用模型属性和路径来映射属性,如下所示:
ViewController:
@GetMapping("/login")
public String login(Model model){
Login login = new Login();
model.addAttribute("login",login);
return "login";
}
JSP页面:
...
<form:form action="login" method="post" modelAttribute="login">
<form:hidden path="id"/>
<label for="username">UserName</label>
<form:input path="username"/><br>
<label for="password">Password</label>
<form:password path="password"/><br>
<form:button>Login</form:button>
</form:form>
...
现在,当我点击登录按钮时,登录对象被发送到适当的控制器,并相应地返回一条带有一些消息的ResponseEntity对象。处理完成后,页面将刷新并显示ResponseEntity对象中的消息,说“登录成功”。
但是我想以警报的形式显示此消息。 为此,我必须发出AJAX请求,并在成功后通过消息调用警报,但是通过这种方法,我无法再使用modelAttribute,并且AJAX已发送了Login对象,这可能吗?
是否可以使用modelAttribute的功能并发出AJAX请求?
答案 0 :(得分:0)
在挖掘了相同的细节之后,我终于找到了解决方案!
我必须进行以下更改。
Login.jsp-在标记之外添加新的按钮标记
php
// I always program in E_STRICT error mode...
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 1);
// We need to make sure the correct timezone is set, or some PHP installations will complain
if (function_exists('date_default_timezone_set'))
{
// * MAKE SURE YOU SET THIS TO THE CORRECT TIMEZONE! *
// List of valid timezones is here: http://us3.php.net/manual/en/timezones.php
date_default_timezone_set('America/New_York');
}
// Require the framework
require_once 'quickbooks-php-master/QuickBooks.php';
$user = 'test';
$pass = 'test';
// Map QuickBooks actions to handler functions
$map = array(
QUICKBOOKS_ADD_CUSTOMER => array( '_quickbooks_customer_add_request', '_quickbooks_customer_add_response' ),
//QUICKBOOKS_ADD_SALESRECEIPT => array( '_quickbooks_salesreceipt_add_request', '_quickbooks_salesreceipt_add_response' ),
//'*' => array( '_quickbooks_customer_add_request', '_quickbooks_customer_add_response' ),
// ... more action handlers here ...
);
// This is entirely optional, use it to trigger actions when an error is returned by QuickBooks
$errmap = array(
3070 => '_quickbooks_error_stringtoolong', // Whenever a string is too long to fit in a field, call this function: _quickbooks_error_stringtolong()
// 'CustomerAdd' => '_quickbooks_error_customeradd', // Whenever an error occurs while trying to perform an 'AddCustomer' action, call this function: _quickbooks_error_customeradd()
// '*' => '_quickbooks_error_catchall', // Using a key value of '*' will catch any errors which were not caught by another error handler
// ... more error handlers here ...
);
// An array of callback hooks
$hooks = array(
// There are many hooks defined which allow you to run your own functions/methods when certain events happen within the framework
// QuickBooks_WebConnector_Handlers::HOOK_LOGINSUCCESS => '_quickbooks_hook_loginsuccess', // Run this function whenever a successful login occurs
);
$log_level = QUICKBOOKS_LOG_DEBUG;
$soapserver = QUICKBOOKS_SOAPSERVER_BUILTIN; // A pure-PHP SOAP server (no PHP ext/soap extension required, also makes debugging easier)
$soap_options = array( // See http://www.php.net/soap
);
$handler_options = array(
//'authenticate' => ' *** YOU DO NOT NEED TO PROVIDE THIS CONFIGURATION VARIABLE TO USE THE DEFAULT AUTHENTICATION METHOD FOR THE DRIVER YOU'RE USING (I.E.: MYSQL) *** '
//'authenticate' => 'your_function_name_here',
//'authenticate' => array( 'YourClassName', 'YourStaticMethod' ),
'deny_concurrent_logins' => false,
'deny_reallyfast_logins' => false,
); // See the comments in the QuickBooks/Server/Handlers.php file
$driver_options = array( // See the comments in the QuickBooks/Driver/<YOUR DRIVER HERE>.php file ( i.e. 'Mysql.php', etc. )
//'max_log_history' => 1024, // Limit the number of quickbooks_log entries to 1024
//'max_queue_history' => 64, // Limit the number of *successfully processed* quickbooks_queue entries to 64
);
$callback_options = array(
);
$dsn = 'mysqli://root:@localhost/qb';
if (!QuickBooks_Utilities::initialized($dsn))
{
// Initialize creates the neccessary database schema for queueing up requests and logging
QuickBooks_Utilities::initialize($dsn);
// This creates a username and password which is used by the Web Connector to authenticate
QuickBooks_Utilities::createUser($dsn, $user, $pass);
}
$primary_key_of_your_customer = 5;
$Queue = new QuickBooks_WebConnector_Queue($dsn);
$Queue->enqueue(QUICKBOOKS_ADD_CUSTOMER, $primary_key_of_your_customer);
$handler_options = array(), $driver_options = array(), $callback_options = array()
$Server = new QuickBooks_WebConnector_Server($dsn, $map, $errmap, $hooks, $log_level, $soapserver, QUICKBOOKS_WSDL, $soap_options, $handler_options, $driver_options, $callback_options);
$response = $Server->handle(true, true);
function _quickbooks_customer_add_request($requestID, $user, $action, $ID, $extra, &$err, $last_action_time, $last_actionident_time, $version, $locale)
{
$xml = '<?xml version="1.0" encoding="utf-8"?>
<?qbxml version="2.0"?>
<QBXML>
<QBXMLMsgsRq onError="stopOnError">
<CustomerAddRq requestID="' . $requestID . '">
<CustomerAdd>
<Name>ConsoliBYTE, LLC (' . mt_rand() . ')</Name>
<CompanyName>ConsoliBYTE, LLC</CompanyName>
<FirstName>Keith</FirstName>
<LastName>Palmer</LastName>
<BillAddress>
<Addr1>ConsoliBYTE, LLC</Addr1>
<Addr2>134 Stonemill Road</Addr2>
<City>Mansfield</City>
<State>CT</State>
<PostalCode>06268</PostalCode>
<Country>United States</Country>
</BillAddress>
<Phone>860-634-1602</Phone>
<AltPhone>860-429-0021</AltPhone>
<Fax>860-429-5183</Fax>
<Email>Keith@ConsoliBYTE.com</Email>
<Contact>Keith Palmer</Contact>
</CustomerAdd>
</CustomerAddRq>
</QBXMLMsgsRq>
</QBXML>';
return $xml;
}
function _quickbooks_customer_add_response($requestID, $user, $action, $ID, $extra, &$err, $last_action_time, $last_actionident_time, $xml, $idents)
{
// Great, customer $ID has been added to QuickBooks with a QuickBooks
// ListID value of: $idents['ListID']
//
// We probably want to store that ListID in our database, so we can use it
// later. (You'll need to refer to the customer by either ListID or Name
// in other requests, say, to update the customer or to add an invoice for
// the customer.
/*
mysql_query("UPDATE your_customer_table SET quickbooks_listid = '" . mysql_escape_string($idents['ListID']) . "' WHERE your_customer_ID_field = " . (int) $ID);
*/
}
function _quickbooks_salesreceipt_add_request($requestID, $user, $action, $ID, $extra, &$err, $last_action_time, $last_actionident_time, $version, $locale)
{
$xml = '<?xml version="1.0" encoding="utf-8"?>
<?qbxml version="2.0"?>
<QBXML>
<QBXMLMsgsRq onError="stopOnError">
<SalesReceiptAddRq requestID="' . $requestID . '">
<SalesReceiptAdd>
<CustomerRef>
<FullName>Keith Palmer Jr.</FullName>
</CustomerRef>
<TxnDate>2009-01-09</TxnDate>
<RefNumber>16466</RefNumber>
<BillAddress>
<Addr1>Keith Palmer Jr.</Addr1>
<Addr3>134 Stonemill Road</Addr3>
<City>Storrs-Mansfield</City>
<State>CT</State>
<PostalCode>06268</PostalCode>
<Country>United States</Country>
</BillAddres>
<SalesReceiptLineAdd>
<ItemRef>
<FullName>Gift Certificate</FullName>
</ItemRef>
<Desc>$25.00 gift certificate</Desc>
<Quantity>1</Quantity>
<Rate>25.00</Rate>
<SalesTaxCodeRef>
<FullName>NON</FullName>
</SalesTaxCodeRef>
</SalesReceiptLineAdd>
<SalesReceiptLineAdd>
<ItemRef>
<FullName>Book</FullName>
</ItemRef>
<Desc>The Hitchhiker\'s Guide to the Galaxy</Desc>
<Amount>19.95</Amount>
<SalesTaxCodeRef>
<FullName>TAX</FullName>
</SalesTaxCodeRef>
</SalesReceiptLineAdd>
</SalesReceiptAdd>
</SalesReceiptAddRq>
</QBXMLMsgsRq>
</QBXML>';
return $xml;
}
function _quickbooks_salesreceipt_add_response($requestID, $user, $action, $ID, $extra, &$err, $last_action_time, $last_actionident_time, $xml, $idents)
{
// Great, sales receipt $ID has been added to QuickBooks with a QuickBooks
// TxnID value of: $idents['TxnID']
//
// The QuickBooks EditSequence is: $idents['EditSequence']
//
// We probably want to store that TxnID in our database, so we can use it
// later. You might also want to store the EditSequence. If you wanted to
// issue a SalesReceiptMod to modify the sales receipt somewhere down the
// road, you'd need to refer to the sales receipt using the TxnID and
// EditSequence
}
function _quickbooks_error_stringtoolong($requestID, $user, $action, $ID, $extra, &$err, $xml, $errnum, $errmsg)
{
mail('your-email@your-domain.com',
'QuickBooks error occured!',
'QuickBooks thinks that ' . $action . ': ' . $ID . ' has a value which will not fit in a QuickBooks field...');
}
AJAX脚本:
...
<form:form id="myform" action="login" method="post" modelAttribute="login">
<form:hidden path="id"/>
<label for="username">UserName</label>
<form:input path="username"/><br>
<label for="password">Password</label>
<form:password path="password"/><br>
</form:form>
<button id="login-btn">Login</button>
...
控制器:(用于检查登录名是否有效)
$(document).ready(function () {
$("#login-btn").click(function () {
$.ajax({
type: "POST",
url: "login",
data : $("#myform").serialize(),
success: function (data) {
alert(data);
},
error: function(data){
alert(data);
}
});
})
});