我正在尝试利用AJAX请求与服务器对话。我尝试通过包含要发布的值的“编辑”按钮上的click事件传递值。我不断收到错误消息,即使按钮和代码看似正确,也没有指定我的“用户”。
我的代码是此StackOverflow帖子的翻译后的sqlsrv和MSSQL版本:How to pass the value through button to bootstrap modal and update values in mysql database using only php
我的按钮包含正确的值,但没有发布到get-user.php。我的ajax请求的一些示例代码:
$('#editModal').on('show.bs.modal', function (event) {
var modal = $(this);
// Extract the user id from the modal triggering button.
var editButton = $(event.relatedTarget);
var userId = editButton.val();
// Set the user id in the modal (read prior to update
operation).
modal.find('#userId').val(userId);
modal.find('#biography').val(biography);
modal.find('#degreesobtained').val(degreesobtained);
modal.find('#aoi').val(aoi);
modal.find('#schwrk').val(schwrk);
// Fetch the user details and update the modal's content with them.
$.ajax({
method: 'post',
dataType: 'json',
async: false,
url: 'get-user.php',
data: {
'userId': userId
},
success: function (response, textStatus, jqXHR) {
modal.find('.modal-title').text('Edit user ' + response.id);
modal.find('#degreesobtained').val(response.degreesobtained);
modal.find('#aoi').val(response.aoi);
modal.find('#schwrk').val(response.schwrk);
switch (response.approve) {
case 'N':
modal.find('#approveOptionNo').prop('checked', true);
break;
case 'Y': // No break.
default:
modal.find('#approveOptionYes').prop('checked', true);
break;
}
},
error: function (jqXHR, textStatus, errorThrown) {
/*
* If the status code of the response is a custom one, defined by
* the developer - here 420, then the corresponding error message
* is displayed. Otherwise, the displayed message will be a general
* user-friendly one - so, that no system-related infos will be shown.
*/
var message = (jqXHR.status === 420)
? jqXHR.statusText
: 'An error occurred during your request. Please try again.';
displayModalAlert(modal, 'danger', message);
disableModalControls(modal);
},
complete: function (jqXHR, textStatus) {
//...
var message = (jqXHR.status === 600)
? jqXHR.statusText
: 'What the hell.';
}
});
});
get-user.php的相关代码:
// Get the user id.
$userId = $_POST['userId'];
/*
* The SQL statement to be prepared.
*/
$sqluserGrab = 'SELECT *
FROM myTable
WHERE ID = ?';
$statement = sqlsrv_prepare( $conn, $sqluserGrab, array( &$userid));
/*
* Bind variables for the parameter markers (?) in the
* SQL statement that was passed to prepare().
*/
sqlsrv_execute( $statement );
/*
* Fetch data and save it into an array:
*
*/
$user = sqlsrv_fetch_array( $statement, SQLSRV_FETCH_ASSOC);
/*
* When no records are found, fetch_array()
* returns NULL. In this case throw an error.
*/
if (!isset($user)) {
header('HTTP/1.1 420 No user found by the given criteria.');
exit();
}
echo json_encode($user);